[Python] 219. Contains Duplicate II

정지은·2022년 10월 21일
0

코딩문제

목록 보기
11/25

219. Contains Duplicate II

문제

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.
https://leetcode.com/problems/count-and-say/

접근

#딕셔너리

파이썬의 딕셔너리를 이용해, nums[i] 값이 마지막으로 등장한 index를 저장해 둔다. 이후 nums배열을 순회하며 nums[i]가 딕셔너리에 저장되어 있는지 확인하고, 저장되어 있다면 현재의 인덱스와 저장된 인덱스의 차이를 구해 K와 비교한다.

순회가 끝나도록 True가 리턴되지 않았다면 조건에 맞는 배열이 아니라고 판단, False를 리턴한다.

코드

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        d = {}
        
        for i in range(len(nums)):
            if nums[i] in d:
                if abs(d[nums[i]]-i) <= k:
                    return True
            d[nums[i]] = i
            
            
            
        return False

효율성

Runtime: 626 ms, faster than 96.59% of Python3 online submissions for Contains Duplicate II.
Memory Usage: 27.3 MB, less than 32.52% of Python3 online submissions for Contains Duplicate II.

profile
Steady!

0개의 댓글