C++ solution with multimap


  • 0
    M

    class Solution {
    public:
    bool containsNearbyDuplicate(vector<int>& nums, int k)
    {

        multimap<int, int> mm; // val->index
        for (auto i=0; i<nums.size(); ++i)
        {
            mm.insert(pair<int, int>(nums[i], i));
        }
        
        auto pre = mm.end();
        for (auto cur=mm.begin(); cur!=mm.end(); ++cur)
        {
            if (pre != mm.end())
            {
                if (cur->first == pre->first) 
                    if (cur->second - pre->second <= k) 
                        return true;
            }
            pre = cur;
        }
        return false;
    }
    

    };


Log in to reply
 

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