您的位置:首页 > 其它

TwoSum1

2015-11-06 21:17 387 查看

问题描述

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

算法描述

第一种解法

首先我们用一个
List<Node>
存储Node,其中Node的成员变量包括val(数组中的值)和idx(数组值对应的索引+1),然后对这个List按Node.val进行排序,排序之后,我们用两个指针索引
left
right
分别从左和右来判断它们的和是否等于target。

如果等于,直接返回相应的索引(从小到大)

如果大于,right–

如果小于,left++

其代码实现如下:

public int[] twoSum(int[] nums, int target){
if(nums == null || nums.length == 0)
return null;
List<Node> list = new ArrayList<>();
for(int i = 0; i < nums.length; i++){
list.add(new Node(i+1, nums[i]));
}
list.sort(new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
return o1.val - o2.val;
}
});
int left = 0;
int right = nums.length - 1;
while(left < right){
Node node1 = list.get(left);
Node node2 = list.get(right);
int sum = node1.val + node2.val;
if(target == sum){
return new int[]{Math.min(node1.idx, node2.idx),
Math.max(node1.idx, node2.idx)};
}else if(target > sum){
left++;
}else {
right--;
}
}
return null;
}
public class Node{
int idx;
int val;
public Node(int idx, int val){
this.idx = idx;
this.val = val;
}
}


第二种解法

我们采用Hash结构来存储数组中的元素val和对应的索引号idx+1。

如果target - nums[i]不在Map中,则直接把nums[i]和i+1放进Map中

如果target - nums[i]在Map中,则直接返回target - nums[i]对应的
idx
i+1


相应的代码实现:

map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int diff = target - nums[i];
if(map.containsKey(diff)){
return new int[]{map.get(diff), i+1};
}
map.put(nums[i], i+1);
}
return null;
}" data-snippet-id="ext.8d1f812753a04115df01f1e8433b920d" data-snippet-saved="false" data-csrftoken="nURvjSzt-O07nifCL6c8YxB04mRDXqTk8bHs" data-codota-status="done">[code]public int[] twoSumByHash(int[] nums, int target){
if(nums == null)
return null;

Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int diff = target - nums[i];
if(map.containsKey(diff)){
return new int[]{map.get(diff), i+1};
}
map.put(nums[i], i+1);
}
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: