Contains Duplicate II

Problem: Contains Duplicate II

We can record the index where the number last appeared in the dictionary so that we can get the difference of index of duplicate.

Code in Python:

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        dict = {}
        for i, num in enumerate(nums):
            if str(num) not in dict: dict[str(num)] = i
            elif i - dict[str(num)] <= k: return True
            else: dict[str(num)] = i
        return False

results matching ""

    No results matching ""