본문 바로가기

Algorithm/Leetcode

[Top Interview 150 - Hashmap] 219. Contains Duplicate II

[Q] [Easy]

Given an integer array nums and an integer k, 
return true if there are two distinct indices i and j in the array 
such that nums[i] == nums[j] and abs(i - j) <= k.

 

  • 문제가 참 이해가 안갔던 문제..
# Answer

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        
        num_dict = {}

        for i, num in enumerate(nums):
            if num in num_dict and i - num_dict[num] <= k:
                return True
            num_dict[num] = i
        return False