001.Two Sum


package One;


import java.util.Arrays;

/**
* @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));
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值