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

存在重复元素 II #13

Open
Aras-ax opened this issue Mar 9, 2019 · 0 comments
Open

存在重复元素 II #13

Aras-ax opened this issue Mar 9, 2019 · 0 comments

Comments

@Aras-ax
Copy link
Owner

Aras-ax commented Mar 9, 2019

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。

示例 1:

输入: nums = [1,2,3,1], k = 3
输出: true

示例 2:

输入: nums = [1,0,1,1], k = 1
输出: true

示例 3:

输入: nums = [1,2,3,1,2,3], k = 2
输出: false

解答

function containsNearbyDuplicate(nums, k) {
    let hashMap = {};
    return nums.some((item, i) => {
        let j = hashMap[item];
        if (j !== undefined) {
            if (i - j <= k) {
                return true;
            }
        }
        hashMap[item] = 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