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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

猜你喜欢

转载自www.cnblogs.com/aries99c/p/12583763.html