题目:
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.
提示:
此题考察的是对Hash Table的应用。这里给出两种方法,第一种基于unordered_map(HashMap),第二种基于unordered_set(HashSet)。
代码:
unordered_map:
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int, int> unmap; for (int i = 0; i < nums.size(); ++i) { if (unmap.find(nums[i]) == unmap.end()) { unmap[nums[i]] = i; } else { int dis = i - unmap[nums[i]]; if (dis <= k) return true; unmap[nums[i]] = i; } } return false; } };
核心思想就是将数作为键,将数的位置作为值。若遇到相同的数,比较位置差异。
下面是基于unordered_set的方法:
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_set<int> us; for (int i = 0; i < nums.size(); i++) { if (i > k) us.erase(nums[i-k-1]); if (!us.insert(nums[i]).second) return true; } return false; } };
相当于是维护一个大小为k+1的划窗,如果超出了划窗的大小就剔除划窗中的第一个数字。如果在插入新数字时发现已经存在,说明找到了满足要求的数字。