美文网首页
219. Contains Duplicate II

219. Contains Duplicate II

作者: SilentDawn | 来源:发表于2018-08-15 19:00 被阅读0次

    Problem

    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

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

    Code

    static int var = [](){
        std::ios::sync_with_stdio(false);
        cin.tie(NULL);
        return 0;
    }();
    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            int size = nums.size();
            if(size<=1)
                return 0;
            map<int,int> dict;
            for(int i = 0;i < size;i++)
            {
                if(dict.find(nums[i])!=dict.end()){
                    if(i - dict[nums[i]] <= k)
                        return true;
                    else
                        dict[nums[i]] = i;
                }
                else{
                    dict[nums[i]] = i;
                }
                
            }
            return false;
        }
    };
    

    Result

    219. Contains Duplicate II.png

    相关文章

      网友评论

          本文标题:219. Contains Duplicate II

          本文链接:https://www.haomeiwen.com/subject/smtgbftx.html