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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { set<int> s; int t = 0; for(int i = 0; i < nums.size(); i++) { s.insert(nums[i]); if(s.size() == t) { for(int j = i - 1; j >= 0 && j >= i - k; j--) { if(nums[i] == nums[j]) return true; } } t = s.size(); } return false; } }; |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼