30
05/2015
[LeetCode] Contains Duplicate II
Contains Duplicate II
Given an array of integers and an integer k, return true if and only if 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.
解题思路:
可以用一个set记录滑动窗口大小的所有元素,随着滑动窗口往右移,左边的陆续删除,添加右边的。若set中出现相同元素,那么返回true。否则返回false。注意题意中的k是指j-i=k。
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { int len = nums.size(); if(k <= 0 || len<=0){ return false; } set<int> s; for(int i = 0; i<len; i++){ if(s.size()>k){ s.erase(nums[i - k - 1]); } if(s.find(nums[i])!=s.end()){ return true; } s.insert(nums[i]); } return false; } };
转载请注明:康瑞部落 » [LeetCode] Contains Duplicate II
0 条评论