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的滑动窗口,用一个unordered_set维护窗口内的数字判断是否出现重复,使用两个指针

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测试程序源码

相关文章: