/**
* @author zhengpengfei
* @Description: TODO
*
* 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
*
* 题目大意
* 给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。
* 要求:这个函数twoSum必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。
* 请注意一点,你返回的结果(包括index1和index2)都不是基于0开始的。你可以假设每一个输入肯定只有一个结果。
*
* 解题思路
* 主要是创建一个辅助类,该类将用于存储数组中的数值和下标,将该类的数值进行大小排序,然后从首尾开始遍历数组的 相加值并和target比较,找到合适的数值,取出index即可
* @date 2017年2月3日 下午2:51:00
*/
public class solution {
//辅助类 用于排序以及寻找target
public static class AssistClass implements Comparable<AssistClass>{
private int value;
private int index;
public AssistClass(){
}
public AssistClass(int value,int index) {
this.value = value;
this.index = index;
}
@Override
public int compareTo(AssistClass o) {
return this.value - o.value;
}
}
//寻找target的方法
public int [] twoSum (int [] inputArray,int target){
int[] result = {0,0};
AssistClass [] assistClasseArray = new AssistClass[inputArray.length];
for (int i = 0; i < inputArray.length; i++) {
assistClasseArray[i] = new AssistClass(inputArray[i], i);//用于存储
}
//先排序
Arrays.sort(assistClasseArray);
int low = 0;
int hight = inputArray.length - 1;
while (low < hight) {
if (assistClasseArray[low].value + assistClasseArray[hight].value == target) {
if (assistClasseArray[low].index < assistClasseArray[hight].index) {
result[0] = assistClasseArray[low].index + 1;
result[1] = assistClasseArray[hight].index + 1;
}else {
result[0] = assistClasseArray[hight].index + 1;
result[1] = assistClasseArray[low].index + 1;
}
break;
}else if (assistClasseArray[low].value + assistClasseArray[hight].value > target ) {
hight--;
}else {
low++;
}
}
return result;
}
}