仅提供个人的一种解题思路,未必是最优,仅供各位参考!
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* <p>
* ClassName SolutionTwoSum
* </p>
* <p>
* Description 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
* </p>
*
* @author wangxu wangx89@126.com
* <p>
* Date 2014-9-11 下午02:18:39
* </p>
* @version V1.0
*
*/
public class SolutionTwoSum {
/**
* 在提交的过程中,碰到的几类错误,可以借助于此便于自己测试程序 Error: Input: [0,4,3,0], 0 Output: 0, 0 Expected: 1, 4 Error: Input: [-3,4,3,90], 0 Output: 0, 0 Expected: 1, 3 Error: Input: [0,4,3,0], 0
* Output: 1, 1 Expected: 1, 4 Error: Input: [2,1,9,4,4,56,90,3], 8 Output: 4, 4 Expected: 4, 5
*/
public static int[] twoSum(int[] numbers, int target) {
int length = numbers.length;
List<Integer> list = new ArrayList<Integer>();// 实例化一个链表,该链表便于找到了符合要求的两个数字之后能够获取到它们的索引值
for (int i = 0; i < length; i++) {
list.add(numbers[i]);
}
Arrays.sort(numbers);// 将传递进来的数组按照从小到大排序
int numsIndex[] = new int[2];// 存放返回结果的索引数组
for (int i = length - 1; i > 0; i--) {
int count = 0;
int result = target - numbers[i];
// 这里要优化一下,如果result比最小的都还小,那么直接下一轮循环,可以节约时间
if (result < numbers[0]) {
continue;
}
// if (result > 0) {// 说明target还有剩余,那么检索剩余的数是否在链表中,如果在说明找到了,如果不在就还原即可
int index1 = list.indexOf(numbers[i]);// 获取第一个数的索引
if (index1 != -1) {// 因为题目要求返回的索引结果是基于1的,所以要加1
numsIndex[count++] = index1 + 1;
} else {
continue;// 第一个数都不存在,那么直接返回循环
}
// System.out.println("numbers[i]=" + numbers[i]);
// System.out.println("index1=" + index1);
int res = list.lastIndexOf(result);// 返回的索引要注意是从1开始,注意此处之所以使用lastIndexOf()函数是因为要处理numbers数组中有两个相同的数字
if (res != -1) {// 只要不等与-1,说明就找到了这个数字
numsIndex[count] = res + 1;
break;// 找到了两个数,直接跳出循环
} else {
continue;
}
}
// 此处还要考虑一种情况,就是0+0=0的情况
if (target == 0) {
if (list.indexOf(0) != -1) {
numsIndex[0] = list.indexOf(0) + 1;
}
if (list.lastIndexOf(0) != -1) {
numsIndex[1] = list.lastIndexOf(0) + 1;
}
// return numsIndex;
}
Arrays.sort(numsIndex);// 将索引数组排序之后返回
return numsIndex;
}
public static void main(String[] args) {
// 以下是自己的一些测试数据
// 0-10200
// 2 4 6 8 10
int[] numbers = new int[10200 / 2];
int num = 2;
int index = 0;
while (num <= 10200) {
numbers[index++] = num;
num += 2;
}
// for (int n : numbers) {
// System.out.println(n+"****");
// }
// //
// numbers={3,2,4};
// int result[] = twoSum(new int[] { -3, 4, 3, 90 }, 0);
int result[] = twoSum(new int[] { 2, 1, 9, 4, 4, 56, 90, 3 }, 8);
// int result[] = twoSum(numbers, 10);
for (int i : result) {
System.out.println(i);
}
}
}