219. Contains Duplicate II

来源:互联网 发布:好吃的零食 知乎 编辑:程序博客网 时间:2024/06/03 19:27
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.
思想:
用set容器来做 主要set的一个特点是 唯一性 插入的值不会有重复
利用这点 使用find()函数查找当前set容器类是否有该值 来进行判断
AC代码:时间o(n) 空间o(n)
class Solution {public:    bool containsNearbyDuplicate(vector<int>& nums, int k) {        set<int> s;        int len = nums.size();        for(int i=0;i<len;i++){            if(i>k&&!s.empty())  s.erase(nums[i-k-1]);            if(s.find(nums[i])==s.end())                         s.insert(nums[i]);            else                        return true;        }        return false;    }};


原创粉丝点击