c++ O(n) short solution using unordered_map


  • 0
    H
    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            unordered_map<int, int> um; // first: element value, second: last location(idx)
            for(int i = 0; i < nums.size(); i ++) {
                if(um.count(nums[i]) > 0 && um[nums[i]] >= i - k) return true;
                um[nums[i]] = i;
            }
            return false;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.