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
翻譯:從有序數(shù)組中找到兩個數(shù)使它們的和為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,時間復(fù)雜點
public int[] twoSum(int[] numbers, int target) { int[] my = new int[2]; // <數(shù)值,下標(biāo)> 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; }新聞熱點
疑難解答