学会思考
刻意练习
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * @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;
    }
};

  

posted on   Worty  阅读(220)  评论(0编辑  收藏  举报
努力加载评论中...

点击右上角即可分享
微信分享提示