Day045 - 219. Contains Duplicate II
업데이트:
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.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
Constraints:
1 <= nums.length <= 105-109 <= nums[i] <= 1090 <= k <= 105
내 풀이
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
"""
같은 원소들간의 거리가 k보다 작은게 있기만 하면 True.
요소들의 dict를 만들고 순회하며 나올 때 마다 거리를 계산.
k보다 작거나 같은 거리가 나오는 순간 return True.
끝까지 다 순회했는데 나오지 않는다면 return False.
"""
check_dict = {}
cal_dist = len(nums)
for idx, num in enumerate(nums):
if num not in check_dict:
check_dict[num] = idx
else:
cal_dist = min(cal_dist, idx-check_dict[num])
if cal_dist <= k:
return True
check_dict[num] = idx
return False
# Time Complexity : \(O(N)\)
댓글남기기