My C++ answer by using Hash table implemented by unordered_map


  • 0
    H

    class Solution {
    public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
    unordered_map<int, int> numsHash;
    for(int i = 0; i < nums.size(); i++)
    {
    if (numsHash[nums[i]])
    {
    if( i + 1 - numsHash[nums[i]] <= k) return true;
    else numsHash[nums[i]] = i + 1;
    }
    else numsHash[nums[i]] = i + 1;
    }
    return false;
    }
    };


Log in to reply
 

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