LeetCode(219) Contains Duplicate II

题目

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.

分析

题目描述:给定一个整数序列,查找是否存在两个下标分别为ij的元素值nums[i]=nums[j]且满足ij的距离最大为k

定义一个长度最大为k的滑动窗口,用一个unordered_set维护窗口内的数字判断是否出现重复,使用两个指针startend标记滑动窗口的两端,初始都是0,然后end不断进行扩展,扫描元素判断是否出现重复元素,直到发现endstart>k, 就开始移动start,并且在set中移除对应的元素。如果以为扫描到数组末尾还没有发现重复元素,那就可以返回false。时间复杂度和空间复杂度都是ON

AC代码

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        if (nums.empty())
            return false;

        int sz = nums.size();
        //使用容器unordered_set 其查找性能为常量
        unordered_set<int> us;
        int start = 0, end = 0;
        for (int i = 0; i < sz; ++i)
        {
            if (us.count(nums[i]) == 0)
            {
                us.insert(nums[i]);
                ++end;
            }
            else{
                return true;
            }

            if (end - start > k)
            {
                us.erase(nums[start]);
                ++start;
            }
        }//for
        return false;

    }
};

GitHub测试程序源码

原文地址:https://www.cnblogs.com/shine-yr/p/5214752.html