[LeetCode] 219. Contains Duplicate II

来源:互联网 发布:2016网络流行词有哪些 编辑:程序博客网 时间:2024/06/03 23:47

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.

// 由于题干限定了最大距离差为k,所以核心思想是维护一个“滑动窗口”class Solution {public:    bool containsNearbyDuplicate(vector<int>& nums, int k) {        unordered_set<int> set;        for (int i = 0; i < nums.size(); i++) {            if (i > k) set.erase(nums[i - k - 1]);            if (set.insert(nums[i]).second == false) return true;        }        return false;    }};

这里写图片描述这里写图片描述