219. Contains Duplicate II

来源:互联网 发布:jenkins 远程windows 编辑:程序博客网 时间:2024/06/03 17:04

Given an array of integers and an integer k, find out whether there are two distinct indicesi andj in the array such that nums[i] = nums[j] and theabsolute difference betweeni and j is at mostk.

Approach #1

public:    bool containsNearbyDuplicate(vector<int>& nums, int k) {        unordered_set<int> s;        int n=nums.size();        if(k<=0)return false;//不存在这样的情况        for(int i=0;i<n;i++)        {            if(i>k) s.erase(nums[i-k-1]);//前面的数据已经超出了范围,即使找到相同的数也不符合条件<=k            if(s.find(nums[i])!=s.end())return true;//找到重复值,因为范围外的数据已经被删除,所以不比判断下标            else s.insert(nums[i]);        }        return false;    }
注意k<0,无解,k=0时,不符合题意distinct indices i and j


也可以用map存放数据,把下标存进去,判断下标

原创粉丝点击