MENU

LeetCode219. Contains Duplicate II(滑动指针)

2019 年 03 月 02 日 • 阅读: 1157 • LeetCode阅读设置

LeetCode219. Contains Duplicate II(滑动指针)

  • Easy
  • Accepted:181,620
  • Submissions:525,006

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 absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

链接

https://leetcode.com/problems/contains-duplicate-ii/

题意

给定一个数组nums和一个数k,查询数组中是否存在两个不同的索引i和j使得nums[i]和nums[j]相等,且i和j之间的差不超过k。

题解

  • 暴力解法,两层循环,时间复杂度$O(n^2)$,准确一点,应该是$O((n-k)*k)$
  • 将其转化成在一个区间[l, l+k]中寻找两个相等的数,那么可以使用滑动窗口来做。因为[l, l+k]区间中总共有k+1个元素,所以我们可以保持滑动窗口的大小不超过k,最大限度将第k+1个元素和窗口中k个元素比较是否相等,即使用unordered_map来查询是否存在。

代码

  • Runtime: 32 ms, faster than 95.45% of C++ online submissions for Contains Duplicate II.
  • Memory Usage: 14.3 MB, less than 80.00% of C++ online submissions for Contains Duplicate II.
class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        int n = nums.size();
        unordered_set <int> uset;
        for (int i = 0; i < n; ++i)
        {
            if (uset.find(nums[i]) != uset.end())
                return true;
            uset.insert(nums[i]);
            if (uset.size() == k + 1) // 保持滑动窗口中始终保持k个元素
                uset.erase(nums[i - k]);
        }
        return false;
    }
};

The end.
2019年3月2日 星期六