Concise C++ 25ms using hash map with short explanation


  • 0
    J
    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
        	unordered_map<int, int> val_pos;	//value to position
        	for(int i = 0; i< nums.size(); i++)
        	{
        		if(val_pos.count(nums[i]))	//repeat exist
        		{
        			if( (i - val_pos[nums[i]])<= k)
        				return true;
    
        			val_pos[nums[i]] = i;
        		}
        		val_pos[nums[i]] = i;
        	}
    
        	return false;
    
        }
    };
    

    The basic idea is to check if the two equal elements are in the range k. If in the range, then return true, if not, update the hash map with the latest index of the number and continue.


Log in to reply
 

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