1. Two Sum 两数之和

题目:Two Sum 两数之和

难度:Easy 简单

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].

题意解析:给定一个数组,返回两个数组中两个元素的下标使得这两个元素的和等于给出的目标数字。假定每一个给定的数组都只有一个正确的答案,并且不能使用同样的元素两次。

作为LeeCode开篇的第一题,这道题目的难度是简单级别的。

解题思路一:

很多人都能第一时间想到答案并将之书写出来。那就是遍历整个数组获得每两个元素的和再与目标数字进行比较,相等则返回。

下面是源代码

public int[] twoSum(int[] nums, int target) {
        int len = nums.length;
        for (int i = 0; i < len-1; i++) {
            for (int j = i+1; j < len; j++) {
                if (nums[i] + nums[j] == target){
                    return new int[]{i, j};
                }
            }

        }
        return null;
    }

此算法的由于进行了双重循环遍历,所以此算法的时间复杂度为O(n²),此算法没有用到额外的存储空间

提交此代码之后:

Runtime: 27 ms, faster than 26.93% of Java online submissions for Two Sum.

Memory Usage: 38.4 MB, less than 52.20% of Java online submissions for Two Sum.

发现运行时间27ms只是超过了26%的用户,这个算法效率可谓很差。

解题思路二:

将所有遍历过的元素都存储在一个集合里边,每次遍历一个新的元素之前都用目标元素的值减去当前元素的值,得到的结果再去集合里边匹配是否存在这样的元素,如果不存在则将当前元素加入集合,否则返回当前这个元素和匹配到的元素的下标。

下面是源代码

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

此算法只进行了一次遍历,时间复杂度为O(n),引入了一个map集合,此集合可能会加入几乎所有的元素,空间复杂度为O(n)。

提交测代码之后:

Runtime: 3 ms, faster than 99.36% of Java online submissions for Two Sum.

Memory Usage: 39.4 MB, less than 16.00% of Java online submissions for Two Sum.

可以看到运行速度只需要3ms比之前的算法效率提高了9倍。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值