classSolution { public: boolcontainsNearbyDuplicate(vector<int> &nums, int k) { int i, j, n = nums.size(); unordered_map<int, vector<int> > num2index;
for (i = 0; i < n; i++) num2index[nums[i]].push_back(i);
for (auto &[_, index_vec] : num2index) { if (index_vec.size() > 1) { n = index_vec.size();
for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if (std::abs(index_vec[i] - index_vec[j]) <= k) { returntrue; } } } } } returnfalse; } };
O(n)
One pass is enough. During traversal, save the last same value, because the index of the last same value is closest to the current index, thus most likely to satisfy abs(i−j)<=k.