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) { unordered_map<int, int> last; int len = nums.size(); for (int i=0; i<len; i++) { int val = nums[i]; auto iter = last.find(val); if (iter == last.end()) { last.insert(make_pair(val, i)); continue; } if (i - iter->second <= k) { return true; } iter->second = i; } return false; } };
第二轮反而写的更挫了:
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_set<int> count; int len = nums.size(); k = min(++k, len); for (int i=0; i<len; i++) { if (i >= k) { count.erase(nums[i-k]); } if (count.count(nums[i]) > 0) { return true; } count.insert(nums[i]); } return false; } };