219.leetcode Contains Duplicate II(easy)[数组 滑动窗口]

来源:互联网 发布:淘宝搜索你会感谢我的 编辑:程序博客网 时间:2024/05/22 14:59

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.

查找数组中距离最大为k的相同的数值,若有则返回true.这里用set存放在k大小的窗口内存在的数值,如果检查的数值在这个set中那么就存在这样的数值。否则每次往前移动一个窗口,知道遍历完一遍数组的所有数据。

class Solution {public:    bool containsNearbyDuplicate(vector<int>& nums, int k) {        //用start和end定义一个滑动窗口,这个窗口里面放的是当前距离内用于判断的可用数值,然后对每个数据判断在窗口里面是否重复        int n = nums.size();        if(k<=0) return false;        set<int> wi;        int start = 0;        int end = 0;        for(int i=0;i<n;i++)        {            if(wi.count(nums[i])==0)            {                wi.insert(nums[i]);                ++end;            }else                return true;            if(end-start>k)            {                wi.erase(nums[start]);                ++start;            }                        }        return false;    }};


0 0
原创粉丝点击