题目:
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:采用了排序算法加上二分查找得到结果,最快需要O(nlogn)
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] arr = Arrays.copyOf(numbers, numbers.length);
int[] result = new int[2];
Arrays.sort(numbers);
//Arrays.
int i=0;
int j= numbers.length-1;
while(i<j){
if((numbers[i]+numbers[j])>target){
j--;
}else if((numbers[i]+numbers[j])<target){
i++;
}else{
//result[0] = i+1;
//result[1] = j+1;
int temp1 = numbers[i];
int temp2 = numbers[j];
int index1=0,index2=0;
boolean flag1 = true;
boolean flag2 = true;
for(int k=0;k<arr.length;k++){
if(flag1){
if(arr[k]==temp1){
index1 = k+1;
flag1 = false;
continue;
}
}
if(flag2){
if(arr[k]==temp2){
index2 = k+1;
flag2 = false;
continue;
}
}
}
if(index1<index2){
result[0] = index1;
result[1] = index2;
}else{
result[0] = index2;
result[1] = index1;
}
break;
}
}
return result;
}
}
方法2:使用hashmap映射表
public class Solution {
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i=0;i<numbers.length;i++){
map.put(numbers[i], i);
}
int[] result = new int[2];
for(int i=0;i<numbers.length;i++){
int waitCal = target-numbers[i];
if(map.get(waitCal)!=null&&map.get(waitCal)>i){
result[0] = i+1;
result[1] = map.get(waitCal)+1;
break;//题目说明最多一个
}
}
return result;
}
}