您的位置:首页 > 其它

LeetCode two sum问题

2017-09-26 10:20 281 查看
问题描述:

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.

例子:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

自己上来就写了个很蠢的算法;

public class Solution {
public  int[] twoSum(int[] nums, int target) {
int[] a=new int[2];
for(int i=0;i<nums.length;i++)
{
for(int j=i+1;i<nums.length;j++)
{
if((nums[i]+nums[j])==target)
{
a[0]=i;a[1]=j;

}

}
}
return a;
}

}


由于,题目已经说了只有其中一对数加起来才会等于target,而且就算有第二对数,加起来等于target,那么发现第一对时就直接返回就行。所以我这个算法写了两个for循环是没有必要的,因为不是找所有。

上传代码后,发现需要时间68ms,打败了8%的人。不过谁让我不多想想呢。

最快,只需8ms的算法所下:

class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
if(nums==null || nums.length<2){
return res;
}

HashMap<Integer, Integer> map = new HashMap<>();
for(int i=0; i<nums.length; i++){
if(map.containsKey(target-nums[i])){
res[0]=map.get(target-nums[i]);
res[1]=i;
return res;
}else{
map.put(nums[i],i);
}
}

return res;

}
}


只需要9ms的算法所下:

class Solution {
public int[] twoSum(int[] nums, int target) {
int[] ans = new int[2];
HashMap<Integer, Integer> res = new HashMap<>();
for (int i = 0; i < nums.length; i ++){
if (res.containsKey(target - nums[i])){
ans[0] = res.get(target - nums[i]);
ans[1] = i;
return ans;
}
res.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}


这两个算法,基本思想相同,因为只需要找到一对数符合要求,借助hashmap容器,利用contains方法直接找出,当前map中是否有target与当前正在比较数组元素之差,如果有,就get到这个差的value值以及当前数组的索引。

第一个算法稍快,可能在于前者判断了当数组长度不足2的情况。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: