LeetCode two sum问题

布满荆棘的人生 2022-06-08 12:48 256阅读 0赞

问题描述:

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.

例子:

  1. Given nums = [2, 7, 11, 15], target = 9,
  2. Because nums[0] + nums[1] = 2 + 7 = 9,
  3. return [0, 1].

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

  1. public class Solution {
  2. public int[] twoSum(int[] nums, int target) {
  3. int[] a=new int[2];
  4. for(int i=0;i<nums.length;i++)
  5. {
  6. for(int j=i+1;i<nums.length;j++)
  7. {
  8. if((nums[i]+nums[j])==target)
  9. {
  10. a[0]=i;a[1]=j;
  11. }
  12. }
  13. }
  14. return a;
  15. }
  16. }

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

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

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

  1. class Solution {
  2. public int[] twoSum(int[] nums, int target) {
  3. int[] res = new int[2];
  4. if(nums==null || nums.length<2){
  5. return res;
  6. }
  7. HashMap<Integer, Integer> map = new HashMap<>();
  8. for(int i=0; i<nums.length; i++){
  9. if(map.containsKey(target-nums[i])){
  10. res[0]=map.get(target-nums[i]);
  11. res[1]=i;
  12. return res;
  13. }else{
  14. map.put(nums[i],i);
  15. }
  16. }
  17. return res;
  18. }
  19. }

只需要9ms的算法所下:

  1. class Solution {
  2. public int[] twoSum(int[] nums, int target) {
  3. int[] ans = new int[2];
  4. HashMap<Integer, Integer> res = new HashMap<>();
  5. for (int i = 0; i < nums.length; i ++){
  6. if (res.containsKey(target - nums[i])){
  7. ans[0] = res.get(target - nums[i]);
  8. ans[1] = i;
  9. return ans;
  10. }
  11. res.put(nums[i], i);
  12. }
  13. throw new IllegalArgumentException("No two sum solution");
  14. }
  15. }

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

第一个算法稍快,可能在于前者判断了当数组长度不足2的情况。

发表评论

表情:
评论列表 (有 0 条评论,256人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCodeTwo Sum

    这是第一题的python代码,思路是将输入映射成为一个map,数组元素的值为key,下标为value,然后直接去map中查找target减去每一个元素之后的值,在map中找到k