您的位置:首页 > 其它

Two Sum

2013-08-25 23:06 323 查看
//use hashmap, time: o(n), space: o(n)
//if the array if already sorted, we can use two pointers, it will be linear time and space
// through we can use two pointers here, it will be o(nlogn) time and o(n) sapce because we need to keep the index of the array
 public int[] twoSum(int[] numbers, int target) {
// Start typing your Java solution below
// DO NOT write main() function
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = new int[2];
for(int i = 0; i < numbers.length; i++) {
if(!map.containsKey(numbers[i])) {
map.put(target - numbers[i], i);
}else{
result[0] = map.get(numbers[i]) < i ? map.get(numbers[i]) + 1 : i + 1;
result[1] = map.get(numbers[i]) < i ? i + 1 : map.get(numbers[i]) + 1;
break;
}
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: