题目:
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
public static int[] twoSum2(int[] nums, int target) {
int[] result = new int[2];
int length = nums.length;
int[] tempNums = nums.clone();
sortit(tempNums, 0, length -1);
result[0] = 0;
result[1] = 0;
int min = 0;
int max = length -1;
boolean find = false;
while(min < max && !find){
if((tempNums[min] + tempNums[max]) > target){
max--;
}else if((tempNums[min] + tempNums[max]) < target){
min++;
}else{
find = true;
}
}
if(find){
for(int i = 0; i < length; i++){
if(tempNums[min] == nums[i]){
result[0] = i + 1;
break;
}
}
for(int i = 0; i < length; i++){
if(tempNums[max] == nums[i]){
if(tempNums[max] == tempNums[min] && (result[0]==(i+1)) ){
continue;
}
result[1] = i + 1;
break;
}
}
}
if(result[0] > result[1]){
int j = result[0];
result[0] = result[1];
result[1] = j;
}
return result;
}
private static void sortit(int[] list, int left, int right){
if(left< right){
int middle = partition(list, left, right);
sortit(list, left, middle-1);
sortit(list, middle+1, right);
}
}
private static int partition(int[] list, int left, int right) {
int privot = list[left];
while(left < right){
while(left < right && privot <= list[right]){
right--;
}
list[left] = list[right];
while(left < right && privot >= list[left]){
left++;
}
list[right] = list[left];
}
list[left] = privot;
return left;
}
本文介绍了一种解决两数之和问题的有效算法。给定一个整数数组及目标值,该算法通过排序和双指针技巧快速找到两个数,使它们的和等于目标值,并返回这两个数的下标。

被折叠的 条评论
为什么被折叠?



