[Array]Contains Duplicate II

mac2022-06-30  112

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 j is at most k.

利用unordered_set速度会比set速度快很多。

class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { if(k==0) return false; unordered_set<int> st; for(int i=0;i<nums.size();i++){ if(i>k) st.erase(nums[i-k-1]); if(st.find(nums[i])!=st.end()){ return true; } st.insert(nums[i]); } return false; } };

转载于:https://www.cnblogs.com/GoFly/p/5751068.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)