動機
lambda加map好方便
Problem
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9Output: [0,1]Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6Output: [0,1]
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
- Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than
O(n2)
time complexity?Sol
先把原本的index加到list,之後sort 做two pointer
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
nums = [(n,i) for (i,n) in enumerate(nums)]
nums.sort(key=lambda a: a[0])
i,j = [0, len(nums)-1]
while i < j:
if nums[i][0]+nums[j][0] == target:
return [nums[i][1], nums[j][1]]
elif nums[i][0]+nums[j][0] >= target:
j -= 1
else:
i += 1