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.
例子:
自己上来就写了个很蠢的算法;
由于,题目已经说了只有其中一对数加起来才会等于target,而且就算有第二对数,加起来等于target,那么发现第一对时就直接返回就行。所以我这个算法写了两个for循环是没有必要的,因为不是找所有。
上传代码后,发现需要时间68ms,打败了8%的人。不过谁让我不多想想呢。
最快,只需8ms的算法所下:
只需要9ms的算法所下:
这两个算法,基本思想相同,因为只需要找到一对数符合要求,借助hashmap容器,利用contains方法直接找出,当前map中是否有target与当前正在比较数组元素之差,如果有,就get到这个差的value值以及当前数组的索引。
第一个算法稍快,可能在于前者判断了当数组长度不足2的情况。
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的情况。
相关文章推荐
- Leetcode之Two Sum II - Input array is sorted 问题
- leetcode--two_sum问题
- 【leetcode】小白题解:two sum问题
- LeetCode Two Sum II - Input array is sorted(Two pointer问题)
- leetcode系列:twosum问题
- leetcode之Two Sum问题
- leetcode之TwoSum问题
- leetcode中第一题twosum问题解答算法的可行性证明
- 【Leetcode】之Two Sum问题
- Leetcode问题-1(Two Sum)
- LeetCode题解 || Two Sum问题
- Leetcode-Two Sum(2 Sum) 问题
- leetcode之twosum问题
- leetcode刷题,我的解法1 twosum问题
- Leetcode-Two Sum——K Sum问题
- two sum @leetcode
- leetcode 167. Two Sum II - Input array is sorted python
- leetcode之Median of Two Sorted Arrays问题
- 【LeetCode 1 : Two Sum】
- Two Sum IV - Input is a BST问题及解法