C++ 6 line solution. simple code and easy understanding


  • 30
    L
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        set<int> cand;
        for (int i = 0; i < nums.size(); i++) {
            if (i > k) cand.erase(nums[i-k-1]);
            if (!cand.insert(nums[i]).second) return true;
        }
        return false;
    }

  • 2
    R

    Sliding window, nice


  • 13
    F

    Hi! here is my short C++ solution using hashMap.

    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, int> hashMap;
        for(int i = 0; i < nums.size(); ++i) {
            if(hashMap.find(nums[i]) != hashMap.end() && i - hashMap[nums[i]] <= k)  return true;
            hashMap[nums[i]] = i;
        }
        return false;
    }

  • 0

    Thank you for your solution, but could you tell me cand.insert(nums[i]).second , what is .second represents? Is cand.insert(nums[i]).second equal to number of nums[i] existed in cand ?


  • 0

    Is .second means whether success to insert nums[i]?


  • 0

    I have figured it out. Many thanks for your solution.


  • 0
    V

    Thanks. I am also performing sliding window but without maintaining set, my question here is what prompted you to go for this O(k) space solution when there is nothing mentioned. Did you try O(1) space solution before?


  • 0
    M

    Can you please explain what this .second means here?


  • 0
    J

    can anybody explain what's the meaning of the code
    if(!set.insert(nums[i]).second)
    what does the SECOND mean?
    Thanks a lot


  • 2
    J

    @jcheng.atl
    I searched online and found the answer.
    The pair::first will store either the newly inserted element or the elements that has its same value in the set.
    The pair::second will indicate the success or failure of inserting the new value.
    We can use the followings:
    if(!set.insert(item).second){
    the content of insert failure to user;
    }
    Thanks


  • 0
    W

    @lchen77 very nice,I understand,thank you.


  • 0
    Y

    if you do not use the STL often, review it and you will found it's so easy.


  • 0

    @fastcode same code!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.