Given an array of integers and a integer K, find out whether there is II distinct indices i and J in the array such that nums[i] = Nums[j] and the difference between I and Jare at most K.
The main idea of the topic: give you an int array and k, see if there are two different indexes in the array I and J make the difference between Nums[i]=nums[j],i and J, up to K
The first thing to think about is a one-digit ratio, with two for loops to get the results. But this method takes too long to submit. Then you need to consider building a Multimap
Save the value and index of the array inside, so it's much faster. Granted, the submission was also passed
classSolution { Public: BOOLContainsnearbyduplicate (vector<int>& Nums,intk) {if(Nums.size () <2|| k<1)return false; Else{Multimap<int,int>Mulm; for(inti =0; i < nums.size (); + +i) Mulm.insert (Make_pair (nums[i], i)); for(inti =0; i < nums.size (); + +i) {Auto CNT=Mulm.count (Nums[i]); Auto ITER=Mulm.find (Nums[i]); while(--CNT) { intPre = Iter->second; intReal = (++iter)->second-Pre; if(Real <= k)return true; } } } return false; }};
Leetcode Contains Duplicate II