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
思路:1、将数组放入hash表,遍历数组,在hash表中查找另一个数。hash查找速度较快
2、利用快排先将数组排序,双向遍历,找到两数之和为target的两个数m,n ,再遍历原数组,找到m,n的下标
----------转载---------
<pre name="code" class="java">public class Solution {
public int[] twoSum(int[] numbers, int target) {
int []result = new int[2];
java.util.HashMap<Integer, Integer> table = new java.util.HashMap<Integer, Integer>(200000);
for (int i = 0; i < numbers.length; i++) {
table.put(numbers[i], i+1);
}
for (int i = 0; i < numbers.length; i++) {
if(table.get(target-numbers[i])!=null&&table.get(target-numbers[i])!=i+1){
result[0]=i+1;
result[1]=table.get(target-numbers[i]);
break;
}
}
return result;
}
}
</pre><pre name="code" class="java">---------my coding time limit exceeded ---------
public class Solution1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] num={2,3,4,5,6,8,9};
Solution1 s=new Solution1();
int[] indexs= s.twoSum(num, 10);
System.out.println(indexs[0]+" "+indexs[1]);
}
public int[] twoSum(int[] numbers, int target) {
int length=numbers.length;
int[] sortNum=numbers;
sortNum=quickSort(sortNum,0,length-1);
int[] index=new int[2];
int split1=0,split2=0,index1=0,index2=0;
for(int i=0;i<length-1;i++){
if(2*sortNum[i]<=target && 2*sortNum[i+1]>target){
split1=i;
}
if(sortNum[i]>target){
split2=i;
break;
}
}
if(split2==0){
split2=length;
}
index1=0;index2=split1;
while(index1<split1 && index2<split2 ){
if(sortNum[index1]+sortNum[index2] <target){
index1++;
if(index1==split1){
index1=0;
index2++;
}
}else if(sortNum[index1]+sortNum[index2] >target){
index1=0;
index2++;
}else{
index[0]=sortNum[index1];
index[1]=sortNum[index2];
break;
}
}
if(index[0]!=0 && index[1]!=0){
for(int i=0;i<numbers.length;i++){
if(numbers[i]==index[0])
index[0]=i+1;
if(numbers[i]==index[1])
index[1]=i+1;
}
if(index[0]>index[1]){
int temp=index[0];
index[0]=index[1];
index[1]=temp;
}
}
return index;
}
int[] quickSort(int[] num,int left,int right){
if(left<right){
int i=left,j=right,x=num[left];
while(i<j){
while(i<j && num[j]>=x)
j--;
if(i<j)
num[i++]=num[j];
while(i<j && num[i]<x)
i++;
if(i<j)
num[j--]=num[i];
}
num[i]=x;
quickSort(num,left,i-1);
quickSort(num,i+1,right);
}
return num;
}
}
</pre><pre name="code" class="java">