letcode 001

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.

 

1 nums = [2, 7, 11, 15], target = 9,  #exam
2 
3 nums[0] + nums[1] = 2 + 7 = 9,#reason
4 return [0, 1] #result

 

最优解o(n):

  

 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         tmp_num = {}
 9         for i in range(len(nums)):
10             if target-nums[i] in tmp_num:
11                 return [tmp_num[target-nums[i]],i]
12             else:
13                 tmp_num[nums[i]] = i   
14         return (-1,-1)
15         

 

运行结果(time):

Runtime: 31 ms

方法一:

  思路:1.当我们看到这个列表(数组)时候,除了暴力求解的方法外,若要得到更优的解,那么就需要考虑,能否多拿出多的空间来换取时间。

      2.既然要让该列表(数组)里面的两个数相加得到目标值,但是我们在遍历该数组的时候,每次只能拿到数组里面的一个值,这个时候,我们就需要花另外的空间去记录下来我们已经遍历过了的值,这样,就可以在我们自己创造的这个空间里,进行筛选。那么用target减去每次遍历的值所得到的值,然后去我们创建的空间里面去筛选。若有,则返回这两个值,若没有,继续向下遍历,直到完成。

     

 

 

 

 

次优解:

 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         tmp_num = nums[:]
 9         tmp_num.sort()
10         index1 = 0
11         index2 = len(nums) - 1
12         while index1 < index2:
13             tmp_target = tmp_num[index1] + tmp_num[index2]
14             if tmp_target == target:
15                 break
16             elif tmp_target > target:
17                 index2 -= 1
18             else: 
19                 
20                 index1 += 1
21         
22         if index1 == index2:
23             return (-1,-1)
24         
25         else:
26             ans1 = nums.index(tmp_num[index1])
27             ans2 = nums.index(tmp_num[index2])
28             
29             if ans1 != ans2:
30                 return [min(ans1,ans2),max(ans1,ans2)]
31             else:
32                 ans2 = nums[ans1+1:].index(tmp_num[index2])
33                 return [ans1,ans1+1+ans2]

 

Runtime: 43 ms

 

思路:

  1.需要两个数的和去与目标值对比,如何在列表中获得两个值:引用两个下标。

  2.由于数组无序,所要我们需要将数组排序以后,在进行比较,否则就成了暴力求解了。注意:排序之后数据的顺序会发生变化,所以我们要记录值

      3.排好序之后,就成了有序列表 例如   [1,2,3,4,5]

  4.一步一步的逼进目标值  取最小的和最大的相加得到结果以后,与target对比。原因:若比target大,最小的不能动(已经是最小了,挪不动了),最大的可以往小的地方挪一位。同理。若比target小,要让结果增大怎么办?大的挪不动(因为此时已经最大),只能将小的往大的方向挪。

  5.特殊情况:[1,2,3,3,5]   当有两个相等的值的时候,我们得到的值是3(要注意此时的数组的顺序已经发生了变化(排序过后的数组))   so  我们需要将原数组后面的3给解放出来---->[1,2,3,3,5]  得到3 。 然后,得到原来数组第一个3的索引,然后将原数组第一个3之后另一个3的索引给拿出来。注意:要将根据第一个3切片的索引加上去,返回结果。

  

 

 

  

 

    

  

posted @ 2018-04-13 17:32  shadowsmile  阅读(183)  评论(0编辑  收藏  举报