标签:
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
java:
public int[] twoSum(int[] numbers, int target) {
if(null!=numbers && numbers.length>0){
int index1 =0,index2=0;
boolean findResult = false;
for(int i=0,len=numbers.length-1;i<len;i++){
index1=i;
for(int j=i+1,len2=numbers.length;j<len2;j++){
index2=j;
if(numbers[index1]+numbers[index2]==target){
findResult = true;
break;
}
}
if(findResult){
break;
}
}
if(0!=index2){
return new int[]{index1,index2};
}
}
return null;
}
public int[] twoSum2(int[] numbers, int target) {
int lenL = numbers.length/2;
int lenR = numbers.length/2+1;
if(numbers.length==2){
lenL=0;
lenR=1;
}
if(numbers[lenL]+numbers[lenR]==target){
return new int[]{lenL,lenR};
}else if(numbers[lenL]+numbers[lenR]>target){
int [] numCopy = new int[lenR];
System.arraycopy(numbers, 0, numCopy, 0, lenR);
return this.twoSum2(numCopy, target);
}else{
int [] numCopy = new int[lenR];
System.arraycopy(numbers, lenL, numCopy, 0, numbers.length-lenL);
int [] numResult = this.twoSum2(numCopy, target);
numResult[0]+=lenL;
numResult[1]+=lenL;
return numResult;
}
}
标签:
原文地址:http://www.cnblogs.com/shisw/p/4316871.html