C++ with multimap, very clearly solution.


  • 0
    A
    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            bool flag = false;
            if(nums.size() == 0 || nums.size() == 1){ return flag; }
            multimap<int, int> imap;
            for(int i = 0; i != nums.size(); ++i){ imap.insert( make_pair(nums[i], i) ); }
            multimap<int, int>::iterator beg1 = imap.begin();
            multimap<int, int>::iterator beg_tmp = beg1;
            ++beg_tmp;
            multimap<int, int>::iterator beg2 = beg_tmp;
            for(; beg2 != imap.end(); ++beg1, ++beg2 ){
                if(beg1->first == beg2->first && beg2->second - beg1->second <= k){
                    flag = true;
                    break;
                }
            }
            return flag;
        }
    };
    

Log in to reply
 

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