1319. Contains Duplicate II

描述

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.

您在真實的面試中是否遇到過這個題?  

樣例

Given nums = [1,2,1], k = 0, return false.

無難度題

class Solution {
public:
    /**
     * @param nums: the given array
     * @param k: the given number
     * @return:  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
     */
    bool containsNearbyDuplicate(vector<int> &nums, int k) {
        // Write your code here
        unordered_map<int,int> mmap;
        
        for(int i=0;i<nums.size();i++){
            if(mmap.find(nums[i])!=mmap.end()&&i-mmap[nums[i]]<=k) return true;
            mmap[nums[i]]=i;
        }
        return false;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章