LeetCode每日一题

Posted Aries99C

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode每日一题相关的知识,希望对你有一定的参考价值。

1.两数之和

题目:

给定一个整数数组nums和一个目标值target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

思路:

由于哈希查找的时间复杂度为O(1),可以利用map降低时间复杂度。

根据与target的差对数组中的数字进行映射,当出现和为target的一组数时,马上就可以返回这组数。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i< nums.length; i++) {
            // 发现符合条件的序对,将其返回
            if(map.containsKey(target - nums[i])) {
                return new int[] {map.get(target-nums[i]),i};
            }
            // 目前映射中对i不存在符合的键,将nums[i]-i加入map
            map.put(nums[i], i);
        }
        // 若无解应当抛出异常
        throw new IllegalArgumentException("No two sum solution");
    }
}

// 作者:guanpengchn
//链接:https://leetcode-cn.com/problems/two-sum/solution/jie-suan-fa-1-liang-shu-zhi-he-by-guanpengchn/
//来源:力扣(LeetCode)
//著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

以上是关于LeetCode每日一题的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode9月 每日一题

LeetCode9月 每日一题

算法·每日一题(详解+多解)-- day14

算法·每日一题(详解+多解)-- day14

leetcode每日一题-495:提莫攻击

leetcode每日一题-299:猜数字游戏