Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2
翻译:从有序数组中找到两个数使它们的和为target
法1:O(n)
public int[] twoSum(int[] numbers, int target) { int[] my = new int[2]; boolean flag =true; int i=0,j=numbers.length-1; while(flag){ while( (numbers[i]+numbers[j])>target ) j--; while( (numbers[i]+numbers[j])<target ) i++; if( (numbers[i]+numbers[j])== target ) flag =false; } my[0] =i+1; my[1] =j+1; return my; }法2:借助 Map,时间复杂点
public int[] twoSum(int[] numbers, int target) { int[] my = new int[2]; // <数值,下标> Map<Integer, Integer> map = new HashMap<>(); for(int i=0;i<numbers.length;i++) map.put(numbers[i], i); int i1=0,i2=0; boolean flag =true; while(flag){ if(map.containsKey(target-numbers[i1])) { i2=map.get(target-numbers[i1]); flag = false; } else i1++; } my[0] = i1+1; my[1] = i2+1; return my; }新闻热点
疑难解答