Two Sum
Given an array of integers, 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.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
AC代码:
import java.util.Arrays;
class Pair implements Comparable<Pair>{
int val;
int index;
public Pair( int val, int index ){
this.val = val;
this.index = index;
}
@Override
public int compareTo(Pair other) {
// TODO Auto-generated method stub
return this.val - other.val;
}
}
public class Solution {
public int[] twoSum(int[] numbers, int target){
int result[] = new int[2];
//store index
int index[] = new int[numbers.length];
//relate number and index
Pair pairs[] = new Pair[numbers.length];
for( int i=0; i<numbers.length; i++){
pairs[i] = new Pair(numbers[i],i+1);
}
//1 sort
Arrays.sort(pairs);
//2 find index
int pre = 0, last = numbers.length-1;
while( pre < last ){
if( pairs[pre].val + pairs[last].val == target ){
if( pairs[pre].index < pairs[last].index){
result[0] = pairs[pre].index;
result[1] = pairs[last].index;
}else{
result[0] = pairs[last].index;
result[1] = pairs[pre].index;
}
break;
}else if( pairs[pre].val + pairs[last].val < target){
pre++;
}else if( pairs[pre].val + pairs[last].val > target ){
last--;
}
}
return result;
}
}
超时代码(时间复杂度O(n*n)):
public int[] twoSum(int[] numbers, int target){
int result[] = new int[2];
for( int i=0; i<numbers.length; i++ ){
for( int j=i+1; j<numbers.length; j++){
if( numbers[i]+numbers[j] == target ){
result[0] = i+1;
result[1] = j+1;
break;
}
}
}
return result;
}