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 difference between i and j is at most k.

Solution:

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        map<int, int> record;
        int n = nums.size();
        for ( int i = 0; i <= n-1; i++ ) {
            if ( record.find(nums[i]) == record.end() ) record[nums[i]] = i;
            else {
                if ( i - record[nums[i]] <= k ) return true;
                else record[nums[i]] = i;
            }
        }
        return false;
    }
};

results matching ""

    No results matching ""