【leetcode】219. 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.


思路:
一开始读题不认真,我以为是重复元素的数组index之差等于k,但原来是at most k,实际上问题比我想象的更简单了。用数据结构unordered_map来存储元素值以及数组下标。剩下的就很容易了。


代码实现:

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, int> my_map;
        for (int i = 0; i < nums.size(); ++i){
            if (my_map.find(nums[i]) == my_map.end()){
                my_map[nums[i]] = i;
            }else{
                if (i - my_map[nums[i]] <= k){
                    return true;
                }else{
                    my_map[nums[i]] = i;
                }
            }
        }
        
        return false;
    }
};
原创文章 299 获赞 2 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zxc120389574/article/details/106066999