数组元素相等,且最大间隔不大于k;

/**
 * @brief 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.
 * 
 * example1:
 * input :nums[1,2,3,1],k=3
 * Output:true
 * 
 * example2:
 * input:nums[1,0,1,1],k=1
 * output:true
 * 
 * example3:
 * Input:nums[1,2,3,1,2,3],k=2
 * output:false
 */
class Solution{
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k){
        unordered_map<int,int> m;
        for(int i = 0; i < nums.size(); i++){
            int n = nums[i];
            if(m.find(n) != m.end() && i - m[n] <=k){
                return true;
            }
            m[n] = i;
        }
        return false;
    }
};

  

猜你喜欢

转载自www.cnblogs.com/hujianglang/p/12456874.html