1.Two Sum
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].
Solution:
时间复杂度为nlog(n),算法为一次排序+相向双指针
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
leftP = 0
rightP = len(nums)-1
result = sorted(enumerate(nums), key=lambda x:x[1])
while leftP < rightP:
if result[leftP][1]+result[rightP][1] == target:
return [result[leftP][0],result[rightP][0]]
elif result[leftP][1]+result[rightP][1] > target:
rightP = rightP - 1
else:
leftP = leftP + 1
return None
2. 3Sum
Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b