Leetcode-cpp 219. There are duplicate elements II

219. There is a repeating element II

  • topic:

Insert picture description here

  • link

    leetcode

  • solution:

    Use unordered_map, where the key value is nums[i] and the value value is the subscript. If there is no such element in the map, increase it, otherwise compare the absolute value of the difference between the found element subscript and the current subscript is greater than k

  • code


class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        int n = nums.size(), idx = 0;
        unordered_map<int, int> nmap; // key:nums[i], value:index c++中用这个
        for (int i = 0; i < n; ++i) {
            auto iter = nmap.find(nums[i]);
            if (iter != nmap.end()) {
                if (i - iter->second <= k) return true;
                else iter->second = i;
            }
            else nmap[nums[i]] = i;
        }
        return false;
    }
};//思路很棒!!

Guess you like

Origin blog.csdn.net/weixin_43255713/article/details/105524470