Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

two sum #23

Open
mamba-1024 opened this issue May 25, 2020 · 0 comments
Open

two sum #23

mamba-1024 opened this issue May 25, 2020 · 0 comments

Comments

@mamba-1024
Copy link
Owner

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

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

示例:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

将数组转存为object,数组的 value 作为 object 的 key,数组的下标作为 object 的 value,
然后去使用 for in 遍历 object,只用 in 判断 value 是否在 object 中。
in使用说明

var twoSum = function(nums, target) {
    let result = {};
    let length = nums.length;
    for (var i = 0; i < length; i++) {
        let difference = target - nums[i];
        if (difference in result) {
            return [result[difference], i]
        }
        result[nums[i]] = i;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant