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; }
相关文章推荐
- [Leetcode] Two Sum
- [LeetCode题解001]Two Sum
- LeetCode - Two Sum
- Two Sum
- 【LeetCode】Two Sum
- leetcode:Two Sum
- Two Sum
- [LeetCode]Two Sum
- 【Leetcode】Two Sum
- two sum
- leetcode:Two Sum
- LeetCode——01 Two Sum
- [leetcode] Two Sum
- Two Sum
- LeetCode -- Two Sum
- leetcode第一题two sum
- [Leetcode]Two Sum
- Two Sum
- [leetcode] Two Sum
- leetcode---------------Two Sum