167. Two Sum II - Input array is sorted
其实我不知道这道题的point是什么…………
两种方法,hashmap/ two pointers
HashMap
1 public int[] twoSum(int[] numbers, int target) { 2 if(numbers.length == 0) { 3 return null; 4 } 5 int[] res = new int[2]; 6 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 7 for(int i = 0; i < numbers.length; i++) { 8 if(!map.containsKey(target - numbers[i])) { 9 map.put(numbers[i], i); 10 } else { 11 res[0] = map.get(target - numbers[i]) + 1; 12 res[1] = i + 1; 13 return res; 14 } 15 } 16 return res; 17 }
Two pointers
1 public int[] twoSum(int[] numbers, int target) { 2 if(numbers.length == 0) { 3 return null; 4 } 5 int[] res = new int[2]; 6 int walker = 0; 7 int runner = numbers.length - 1; 8 int sum = numbers[walker] + numbers[runner]; 9 while(sum != target) { 10 if(sum > target) { 11 runner--; 12 } else { 13 walker++; 14 } 15 sum = numbers[walker] + numbers[runner]; 16 } 17 res[0] = walker + 1; 18 res[1] = runner + 1; 19 return res; 20 }