Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are NOT zero-based.
Example
numbers=[2, 7, 11, 15], target=9
return [1, 2]
Solution
x = target - numbers[i] 提前一行,就变成了负负的问题了。
(1) solution one we can use the hastable do it with O(n) time and O(n) sapce
(2) we also can do two pointers here, we need to sort it before we do two pointers then lost the ori indexing.
1 3 4 5 6 7
Last updated
Was this helpful?