早就想刷LeetCode了,但一直在拖,新学期开学,开始刷算法。

我准备从Python和C++两种语言刷。一方面我想做机器学习,以后用Python会比较多,联系一下。另一方面C++或者C语言更接近底层,能够让我更深入的理解算法。

1、题目

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15],target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1]

2、Python解法

我是这样写的

  1. class Solution(object):
  2. def twoSum(self,nums,target):
  3. """
  4. :type nums: List[int]
  5. :type target: int
  6. :rtype: List[int]
  7. """
  8. for i in range(0,len(nums)-1):
  9. for j in range(i+1,len(nums)):
  10. if nums[i]+nums[j]==target:
  11. return i,j
  12.  
  13. nums=[2,7,11,15]
  14. target=9
  15. result=Solution()
  16. result_num=result.twoSum(nums,target)
  17. print(result_num)

其中遇到了一个错误

TypeError: twoSum() missing 1 required positional argument: 'target'

这个因为之前我后面几行的代码是

  1. nums=[2,7,11,15]
  2. target=9
  3. result_num=Solution.twoSum(nums,target)
  4. print(result_num)

没有初始化Solution类,改成上面第23行先初始化一下就行了

然而。。。这个代码完全不能通过LeetCode的测试。算法复杂度太高

然后我看了别人写的

  1. class Solution(object):
  2. def twoSum(self,nums,target):
  3. """
  4. :type nums: List[int]
  5. :type target: int
  6. :rtype: List[int]
  7. """
  8. n = len(nums)
  9. result = {}
  10. if n <= 1:
  11. return False
  12. else:
  13. for i in range(n):
  14. if nums[i] in result:
  15. return result[nums[i]],i
  16. else :
  17. result[target-nums[i]]=i
  18.  
  19. nums=[2,7,11,15]
  20. target=9
  21. result=Solution()
  22. result_num=result.twoSum(nums,target)
  23. print(result_num)

就是借用字典的key-value进行的匹配,算法复杂度仅为O(n)

然后还看到了这个

  1. class Solution(object):
  2. def twoSum(self, nums, target):
  3.  
  4. for ind, num in enumerate(nums):
  5. if target-num in nums and nums.index(target-num) != ind:
  6. return [ind, nums.index(target-num)]
  7. return -1

直接利用了列表的索引。

运行速度仅为4ms

但是其中肯定用到了其他遍历比如nums.index(target-num)。这就是Python最大的优势吧。简单,容易理解。

3、C语言解法

说实话,我还没系统的学过C++呢。专业不是这类的,学校不给我们安排课。这次先用C。等我慢慢学学C++再用C++

我的解法:

  1. #include<stdio.h>
  2.  
  3. /**
  4. * Note: The returned array must be malloced, assume caller calls free().
  5. */
  6. int* twoSum(int* nums, int numsSize, int target) {
  7. int i,j;
  8. static int result[];
  9. for(i=;i<numsSize-;i++)
  10. {
  11. for(j=i+;j<numsSize;j++)
  12. {
  13. if(*(nums+i)+*(nums+j)==target)
  14. {
  15. *result = i;
  16. *(result+)=j;
  17. }
  18. }
  19. }
  20. return(result);
  21. }
  22. int main()
  23. {
  24. int nums[]={,,,};
  25. int target = ;
  26. int numSize=;
  27. int *result;
  28. result=twoSum(nums,numSize,target);
  29. printf("succeed\n");
  30. for(int i=;i<;i++)
  31. {
  32. printf("%d\n",*(result+i));
  33. }
  34.  
  35. return ;
  36. }

只是简单的遍历。丝毫没有新意

大神解法:

  1. /**
  2. * Note: The returned array must be malloced, assume caller calls free().
  3. */
  4.  
  5. int* twoSum(int* nums, int numsSize, int target) {
  6. int i, max, min;
  7. max = min = nums[];
  8. for(i = ; i < numsSize; i++) {
  9. if(nums[i] > max) max = nums[i];
  10. if(nums[i] < min) min = nums[i];
  11. }
  12.  
  13. int *map = (int*)calloc((max-min+), sizeof(int));
  14. int *reval = (int*)malloc(sizeof(int)*);
  15.  
  16. for(i = ; i < numsSize; map[nums[i]-min] = ++i) {
  17. int lookfornum = target - nums[i];
  18. if(lookfornum < min || lookfornum > max) continue;
  19. int dis = lookfornum - min;
  20. if (map[dis]) {
  21. reval[] = i;
  22. reval[] = map[dis] -;
  23. break;
  24. }
  25. }
  26.  
  27. return reval;
  28.  
  29. }

这个是所有解法里运行的最快的了。引用了我根本没听说过的map。我也很无奈呀。还要注意内存的申请呀。不过我好像没看到free

今天比较晚了。我还想再画画程序流程图的,既然做了,就要做透。

LeetCode——Problem1:two sum的更多相关文章

  1. Java for LeetCode 216 Combination Sum III

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

  2. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  3. [leetCode][013] Two Sum 2

    题目: Given an array of integers that is already sorted in ascending order, find two numbers such that ...

  4. [LeetCode] #167# Two Sum II : 数组/二分查找/双指针

    一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...

  5. [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针

    一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...

  6. [array] leetcode - 40. Combination Sum II - Medium

    leetcode - 40. Combination Sum II - Medium descrition Given a collection of candidate numbers (C) an ...

  7. [array] leetcode - 39. Combination Sum - Medium

    leetcode - 39. Combination Sum - Medium descrition Given a set of candidate numbers (C) (without dup ...

  8. LeetCode one Two Sum

    LeetCode one Two Sum (JAVA) 简介:给定一个数组和目标值,寻找数组中符合求和条件的两个数. 问题详解: 给定一个数据类型为int的数组,一个数据类型为int的目标值targe ...

  9. [leetcode]40. Combination Sum II组合之和之二

    Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...

随机推荐

  1. 梦织未来Windows驱动编程 第04课 驱动相关的数据结构

  2. Python变量状态保持四种方法

    Python状态保持 ​ 全局 global def tester(start): global state state = start def nested(label): global state ...

  3. 【转】Nginx搭建反向代理服务器过程详解

    阅读目录 1.1 反向代理初印象 1.2 反向代理的作用 2.1 Nginx是神马? 2.2 Nginx的应用现状 2.3 Nginx的核心特点 3.1 准备一个ASP.NET网站部署到IIS服务器集 ...

  4. 【转】ios输入框被键盘挡住的解决办法

    做IOS开发时,难免会遇到输入框被键盘遮掩的问题.上网上搜索了很多相关的解决方案,看了很多,但是由衷的觉得太麻烦了. 有的解决方案是将视图上的所有的东西都添加到一个滚动视图对象( UIScrollVi ...

  5. UVA1629 Cake slicing

    题目传送门 直接暴力定义f[x1][y1][x2][y2]是使对角为\((x1, y1),(x2, y2)\)这个子矩形满足要求的最短切割线长度 因为转移顺序不好递推,采用记忆化搜索 #include ...

  6. Servlet 的生命周期 及 注意事项 总结

    Servlet的生命周期 图解Servlet的生命周期 生命周期的各个阶段 实例化 :Servlet 容器创建 Servlet 的实例 初始化 :该容器调用init() 方法 请求处理 :如果请求Se ...

  7. Websocket教程SpringBoot+Maven整合

    1.大话websocket及课程介绍 简介: websocket介绍.使用场景分享.学习课程需要什么基础 2.课程技术选型和浏览器兼容讲解 简介: 简单介绍什么是springboot.socketjs ...

  8. 01_15_Struts2_带参数的结果集

    01_15_Struts2_带参数的结果集 1. 背景说明 服务器端页面跳转的时候,通过struts提供的标签的valuestack可以直接取.服务器端的转发,valuestack的对象属性可以共享. ...

  9. Python_三级目录

    程序要求: 1. 使用字典存储 1. 可以一层一层的进入到所有层2. 可以在每层返回上一层3. 可以在任意层退出 三级目录写了两个版本,第一个版本是刚看完字典写出来的,代码很多冗余,很多重复. men ...

  10. JS:字符串转成json数据,和json转成字符串方法 iframe获取父级传过来的数据

    字符串转成json数据,和json转成字符串方法 //转为JSON adinfo=JSON.parse(adinfo) //转为字符串 adinfo=JSON.stringify(adinfo) 大概 ...