Find two numbers in the list so the sum can match the target number.
Solution
- 最简单的brute force可以O(N^2)解决
2.使用Hash Table直接做查询
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++){
int other=target - nums[i];
if(map.containsKey(other))
return new int[] {map.get(other),i};
map.put(nums[i],i);
}
throw new IllegalArgumentException("No two sum solution");
}
}```
网友评论