标签:
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 iand j is at most k.
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { if(k<0) return false; if(k>=nums.size()) k=nums.size()-1; unordered_set<int> s; for(int i=0;i<nums.size();i++) { if(i>k) s.erase(nums[i-k-1]);//限制窗口长度为k。 if(s.find(nums[i])!=s.end()) return true;//找集合s中值为nums[i]的元素的位置,如果没有遍历到最后就找到了,则说明其中有重 //复元素 s.insert(nums[i]); } return false; } };
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/46628471