LeetCode-TwoSum

本例代码下载地址:TwoSum下载

题目描述:

在这里插入图片描述
简单地说就是给出一个数字和一个目标数,求数组中符合目标数的任意2个数(不包括自身)在数组中的下标。

解决思路:
常规做法是for循环,通过第一个数值(比如下标为0,1,2……)与剩下数值比对,符合条件的即为答案。时间复杂度为O(n^2)。
代码如下:

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

改进:
我们常说的可以用空间换时间的方式来降低时间复杂度,那么在本例中可不可以呢?
答案是可以的。我们用map来储存用过的数字,这样当target - 当前值 = map中存在的数字时,即可认为储存的数字 = 第一个下标,当前的数字 = 第二个下标。算法复杂度0(n)。文字比较抽象,可以看下图来帮助理解:
在这里插入图片描述
代码实现:

public static int[] twoSumImprove(int[]  nums, int target){
       if (nums.length < 2){
           return null;
       }
       
       HashMap<Integer, Integer> map = new  HashMap<Integer, Integer>();
        int[] result = null;
        for (int i = 0; i < nums.length;  ++i) {
            if (map.containsKey(target -  nums[i])) {
               result = new int[2];
               result[0] = map.get(target -  nums[i]);
               result[1] = i;
                break;
            }
            // 将比较过的数加入map
            map.put(nums[i], i);
        }
        return result;
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值