LeetCode(219) Contains Duplicate II

原创 2015年11月19日 13:36:26

题目

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

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetcode: (219) Contains Duplicate II

【Question】 Given an array of integers and an integer k, find out whether there are two distinct ind...
  • zk031
  • zk031
  • 2015年08月28日 20:50
  • 178

【leetcode】219. Contains Duplicate II

一、题目描述 Given an array of integers and an integer k, find out whether there are two distinct indic...

LeetCode笔记:219. Contains Duplicate II

判断一个数组中一定范围内是否有相同的数字

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...

[leetcode]: 219. Contains Duplicate II

1.题目Given an array of integers and an integer k, find out whether there are two distinct indices i a...

【leetcode】Array——Contains Duplicate II(219)

题目:Given an array of integers and an integer k, find out whether there are two distinct indices i ...

【LeetCode-面试算法经典-Java实现】【219-Contains Duplicate II(包含重复元素II)】

【219-Contains Duplicate II(包含重复元素II)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】代码下载【https://github.com/Wang-...

leetcode题解-217. Contains Duplicate&&219.Contains Duplicate II

题目:Given an array of integers, find if the array contains any duplicates. Your function should retur...

217, 219,220. Contains Duplicate I, II, III

Given an array of integers, find if the array contains any duplicates. Your function should return ...

219. Contains Duplicate II [easy] (Python)

题目链接https://leetcode.com/problems/contains-duplicate-ii/题目原文 Given an array of integers and an int...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode(219) Contains Duplicate II
举报原因:
原因补充:

(最多只允许输入30个字)