[LeetCode]两数之和(Two Sum)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/X_1076/article/details/82221386

题目描述

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums1 = 2 + 7 = 9
所以返回 [0, 1]

解决方案

若a + b = c,则 c - a = b。所以只需记录所有遍历过的数,然后利用预期值-当前值得出的值查询是否已有记录,如果有则退出循环。

    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        // 记录遍历过的数和索引
        Map<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            // 获取target-nums[i],看是否存在,存在则表明可以相加为target
            Integer value = map.get(target - nums[i]);
            if (value != null) {
                res[0] = value;
                res[1] = i;
                break;
            }
            // 用键保存遍历过的数,用值保存遍历过的索引
            map.put(nums[i], i);
        }

        return res;
    }

时间复杂度:O(n)
空间复杂度:O(n)
原文地址:https://lierabbit.cn/2018/04/22/%E4%B8%A4%E6%95%B0%E4%B9%8B%E5%92%8C/

猜你喜欢

转载自blog.csdn.net/X_1076/article/details/82221386
今日推荐