LeetCode Contains Duplicate2


Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.

The original problem is here.

The original code is here.

My Solution

I solve this problem in C++, as below:

*Contains Duplicate2
*Author: shuaijiang
*Email: zhaoshuaijiang8@gmail.com
using namespace std;

class Solution {
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
            return false;
        map<int,int> myMap;
        map<int,int>::iterator mapIter;
        for(int count=0;count<nums.size();++count){
                myMap[nums[count]] = count;
                if(count - myMap[nums[count]] <= k)
                    return true;
                    myMap[nums[count]] = count;
        return false;


To solve the problem, I use a hash(map in C++) to save the num and its index. If a new num is in the map, compute the difference of the index. If the difference is not larger than k, then return true. Finally, if not return true before, then return false.