package One;
/**
* @author jiangfei
*Original Title:
*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].
*
*给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。 要求:这个函数twoIndex必须要返回能够相加等于目标数字的两个数的索引,
*且index1必须要小于index2。
*/public class TwoSum {
/**
* 辅助类
*/
private static class Node implements Comparable<Node> {
int val;// 值
int idx;// 值所对应的下标
public Node(int val, int idx) {
this.val = val;
this.idx = idx;
}
// 比较方法
@Override
public int compareTo(Node o) {
if (o == null) {
return -1;
}
return this.val - o.val;
}
}
public int[] twoIndex(int[] nums, int target) {
//返回数组
int[] result = { 0, 0 };
// 创建辅助数组
Node[] tmp = new Node[nums.length];
for (int i = 0; i < nums.length; i++) {
tmp[i] = new Node(nums[i], i);
}
// 对辅助数组进行排序
Arrays.sort(tmp);
int left = 0;
int right = nums.length - 1;
while (left < right) {
if (tmp[left].val + tmp[right].val == target) {
if (tmp[left].idx > tmp[right].idx) {
result[0] = tmp[right].idx;
result[1] = tmp[left].idx;
} else {
result[0] = tmp[left].idx;
result[1] = tmp[right].idx;
}
break;
} else if (tmp[left].val + tmp[right].val > target) {
right--;
} else if (tmp[left].val + tmp[right].val < target) {
left++;
}
}
return result;
}
public static void main(String[] args) {
int[] nums = {2,7,11,15,8};
int tagert = 19;
int[] twoResult = new TwoSum().twoIndex(nums,tagert);
System.out.println(Arrays.toString(twoResult));
}
}