学习Python的漫漫长路(1)[leetcode,Python]

算法:两数之和

算法描述:

给定一个整数数列,找出其中和为特定值的那两个数。

你可以假设每个输入都只会有一种答案,同样的元素不能被重用。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

我的算法:

 1 def twoSum(nums, target):
 2     i, j ,c= 0,0,0
 3     list=[]
 4     for i in range(0, len(nums)):
 5         for j in range(0, len(nums)):
 6             if (i == j):
 7                 continue
 8             elif (nums[i] + nums[j] == target):
 9                list.append([i,j])
10                c+=1
11     for k in range(0,c):
12         for h in range(0, c):
13             if(k>len(list)-1 or h>len(list)-1):
14                 break
15             list2 = list[h].copy()
16             list2.reverse()
17             if(list[k]==list2):
18                 list.remove(list[h])
19     for i in range(0, len(list)):
20         print(list[i])

 

总结:看似逻辑问题不大,实际上在时间复杂度方面大大的超过了要求,仅能满足约百个数的尝试

CSDN大佬 某晏 的算法:

1 def twoSum(self, nums, target):
2     for i, num in enumerate(nums):
3         sub_num = target - num
4         if sub_num in nums:
5             t_index = nums.index(sub_num)
6             if t_index != i:
7                 return [i, t_index]

 



总结:算法精炼,巧用枚举,活用list的内置方法,复杂度很低!
posted @ 2018-04-02 16:57  Zaric_Chou  阅读(299)  评论(0)    收藏  举报