Contains Duplicate II

Description:

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.

Code:

 1  bool containsNearbyDuplicate(vector<int>& nums, int k) {

 2         unordered_map<int,int>m;

 3         int n = nums.size();

 4         for (int i = 0; i < n; ++i)

 5         {

 6             if ( m.count(nums[i]) && i - m[nums[i]] <= k)

 7                 return true;

 8             else

 9                 m[nums[i]] = i;

10         }

11         return false;

12     }

 

你可能感兴趣的:(contains)