class Solution { public int[] twoSum(int[] numbers, int target) { int flag[] = new int [2]; int l = 0 ; int r = numbers.length-1; while(l<r) { if((numbers[l]+ numbers[r])<target) { l++; } else if((numbers[l]+numbers[r])>target) { r--; } else { flag[0] = l+1; flag[1] = r+1; break; } } return flag; } }
还可用hash表
public int[] twoSum(int[] numbers, int target) { int flag[] = new int [2]; HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>(); for(int i = 0 ; i < numbers.length; i++) { if(hm.containsKey(target-numbers[i])) { flag[0] = hm.get(target-numbers[i])+1; flag[1] = i+1; break; } else{ hm.put(numbers[i],i); } } return flag; } }