LeetCode a daily question (c)

1. The sum of two numbers

topic:

Given an array of integers numsand a target value target, and you figure out a target value of the two integers in the array, and return to their array subscript.

You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.

Ideas:

Since the hash lookup time complexity O(1), it can be used mapto reduce the time complexity.

According to targetan array of digital mapping of the difference, when there is and targetwhen a set of numbers, we can immediately return to the set number.

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)
//著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/two-sum
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/aries99c/p/12583763.html
Recommended