LeetCode笔记 - OJ1 Two-Sum
我们需要查找target-x是否存在于array中,同时返回它的index。需要maintain a map of each element to index。最好的实现方法就是HashTable. JAVA中提供了实现方法:Map类。
- * reduce the look up time from O(n)O(n) to O(1)O(1) by trading space for speed*
Two-Pass HashTable
代码块语法遵循标准markdown代码,例如:
public int[] toSum(int[] nums, int[] target){
Map<Integer, Integer> map = new Map<Integer, Integer>();
for(int i=0; i<nums.length; i++){
map.put(nums[i], i);
}
for(int i=0; i<nums.length; i++){
int result = target - nums[i];//注意判断不包括nums[i]本身
if(map.containsKey(result) && map.get(result)!= i){
return new int[]{i, map.get(result)};
}
}
throw new IllegalArgumentException("No two sum solution");
}