力扣题目链接
跟两数之和好像啊
于是写了一个HashMap
class Solution { public int[] twoSum(int[] numbers, int target) { int[] a = new int[2]; Map<Integer,Integer> map = new HashMap<>(); for(int i=0;i<numbers.length;i++){ if(map.get(target-numbers[i])!=null){ a[0] = map.get(target-numbers[i]); a[1] = i; } map.put(numbers[i],i); } return a; } }
看到运行结果哭了
原来大佬们都是用的双指针直接0ms
class Solution { public int[] twoSum(int[] numbers, int target) { int i = 0,j = numbers.length-1; int[] res = new int[2]; while(i<j){ if(numbers[i] + numbers[j] > target){ j--; } else if(numbers[i] + numbers[j] < target){ i++; } else{ res = new int[]{i,j}; break; } } return res; } }