Contains Duplicate II

Posted jiadyang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Contains Duplicate II相关的知识,希望对你有一定的参考价值。

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

 找两个相等数的间距,间距最大为k,我的思路就是用map来保存index,看代码吧:)

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        int n = nums.size();
        map<int, int> m;
        for (int i = 0; i < n; ++i)
        {
            if (m.find(nums[i]) != m.end())
            {
                if (i - m[nums[i]] <= k)
                    return true;
                else
                    m[nums[i]] = i;
            }
            m[nums[i]] = i;
        }

        return false;
    }
};

 

以上是关于Contains Duplicate II的主要内容,如果未能解决你的问题,请参考以下文章

219. Contains Duplicate II

LeetCode219. Contains Duplicate II

219. Contains Duplicate II

LeetCode Contains Duplicate II

219. Contains Duplicate II

Contains Duplicate II