leetcode1:两数之和

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

 实例:

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

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

1.我的思路:

可以提交但时间复杂度为O(n^2)。其中13到20行为了解决数组里有重复元素时,不能用index的情况。如图

 1 class Solution:
 2     def twoSum(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: List[int]
 7         """
 8         L=sorted(nums)
 9         n = len(L)
10         i, j = 0, n-1    #首尾各一个指针
11         while i<j:       #两指针的元素相加,等于target时,输出索引
12             if L[i] + L[j] == target:      #在([3,3],9)测试为了避免index方法输出的索引
13                 for value in range(n):
14                     if nums[value] == L[i]:
15                         m = value
16                         break
17                 for value in reversed(range(n)):
18                     if nums[value] == L[j]:       
19                         n = value
20                         break
21                 return [m,n]
22             elif L[i] + L[j] < target:
23                 i = i+1
24             elif L[i] + L[j] > target:
25                 j = j-1
26         return 'no answer'
27 solution = Solution()
28 print(solution.twoSum([2,7,11,15],9))

2.参考了答案后的思路:

有重复元素时无法输出正确结果。

 1 class Solution:
 2     def twoSum(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: List[int]
 7         """
 8         d = {}
 9         n = len(nums)
10         for value in nums:
11             if (target-value) not in d:
12                 d[value] = nums.index(value)
13             elif (target-value) in d:
14                 return [nums.index(target-value),nums.index(value)]
15 solution = Solution()
16 print(solution.twoSum([2,7,11,15],9))

猜你喜欢

转载自www.cnblogs.com/gaowanru/p/9210393.html