[LeetCode]Contains Duplicate II

Contains Duplicate II

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

Contains Duplicate类似,多了个判断而已。

注意可能有多个重复,例如[1,0,1,1],1 为 True。

 1 class Solution {
 2 public:
 3     bool containsNearbyDuplicate(vector<int>& nums, int k) {
 4         unordered_map<int,int> showed;
 5         for(int i=0;i<nums.size();i++)
 6         {
 7             if(showed.find(nums[i])!=showed.end())
 8             {
 9                 if((i-showed[nums[i]])<=k)
10                 {
11                     return true;
12                 }
13                 else
14                 {
15                     showed[nums[i]]=i;
16                 }
17             }
18             else
19             {
20                 showed[nums[i]]=i;
21             }
22         }
23         return false;
24     }
25 };
原文地址:https://www.cnblogs.com/Sean-le/p/4742070.html