题目链接:https://leetcode.com/problems/two-sum/#/description
参考他人资料的链接:http://www.cnblogs.com/springfor/p/3859618.html
http://www.jiuzhang.com/solutions/two-sum/
题目描述:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
解题思路:
首先排序,然后再用binarySearch()循环查找,target - nums[i] 的值,找到后就记录当前的i和找到的index;最后经过处理输出。
注意点:
1、这个题给的数组只有一对是符合题目要求的,所以找到就返回;
2、返回值的两个下标要是不同的,例如数组为[3,3];target = 6;返回值应为[0,1]而不是[0,0],所以我调用java中的Arrays.binarySearch(int[] a, int key)时出错。
代码如下所示:
public static int[] twoSum(int[] num , int target){
int len = num.length;
int[] copy = new int[len];
//int[] copy = num; 这样写会出错,copy排序后num也排序了
for(int i = 0 ;i < len ;i++)
copy[i] = num[i];
Arrays.sort(copy);
int[] result = new int[2];
int[] answer = new int[2];
int j = 0;
for(int i = 0 ; i < len;i++){
//防止出现返回值是相同的情况,例如[3,3] target = 9;返回为[0,0];所以不能用binarySearch(int[] a,int key)
int index = Arrays.binarySearch(copy,0,i,target - copy[i]);
int index1 = Arrays.binarySearch(copy,i+1,len,target - copy[i]);
if(index >= 0 || index1 >= 0){
//哪个大于0,谁就是找到后返回的下标
int temp = (index > index1) ?index : index1 ;
//记录哪两个数相加等于target
result[j] = copy[i];
result[j+1] = copy[temp];
break;//找到一对就结束,因为题目说了就是一对
}
}
int index1 = -1,index2 = -1 ;
for(int i = 0;i < len ; i++){
if(num[i] == result[0] && index1 == -1){
index1 = i;
}else if(num[i] == result[1] && index2 == -1){
index2 = i ;
}
}
answer[0] = (index1 < index2) ? index1 : index2 ;
answer[1] = (index1 > index2) ? index1 : index2 ;
return answer ;
}
查考其他人的答案时发现了一个很好的解决方式,用HashMap()实现的,详情见上面的链接