码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Contains Duplicate II

时间:2015-05-30 19:53:03      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   

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

标签:leetcode   c++   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/46277331

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!