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.
这题上上一篇博客的延伸,问的是k长的距离内有没有两个数是相等的,类似一个华栋窗口问题,方法比较简单,使用一个map记下上次数出现的位置就可以了,代码如下:
1 class Solution { 2 public: 3 bool containsNearbyDuplicate(vector<int>& nums, int k) { 4 map<int, int> ret; 5 int sz = nums.size(); 6 for (int i = 0; i < sz; ++i){ 7 if (ret.find(nums[i]) != ret.end() && i - ret[nums[i]] <= k) 8 return true; 9 else 10 ret[nums[i]] = i; 11 } 12 return false; 13 } 14 };
时间: 2024-10-24 05:09:09