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:
배열 nums와 정수 k가 주어졌을 때, nums[i]==nums[j]를 만족하고 abs(i-j) <= k를 만족하는 인덱스가 있는지 판별하는 문제이다.
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
if len(nums)==1:
return False
for i in range(len(nums)):
for j in range(len(nums)):
if i==j:
continue
else:
if nums[i] == nums[j] and abs(i - j) <= k:
return True
return False
최악의 경우 O(n^2)의 시간 복잡도를 가지는 brute-force로 판별하니 당연히 안된다.
nlogn을 보장하기 위해 sort를 해볼까 했지만, 인덱스의 번호가 바뀌어 버린다.
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
dic = collections.defaultdict(int)
for i, v in enumerate(nums):
i += 1
if dic[v] and i - dic[v] <= k:
return True
dic[v] = i
return False
i+=1을 해주는 이유는 다음과 같다.
nums가 123일 경우 dic[1] = 0이 된다.dic[v]는 0이기에 거짓이 된다.i + 1 해준다.if v in nums_dic.keys() and i - nums_dic[v] <= k:
i+=1이 직관적이지 않다면 이런 식으로 쓸 수도 있다.
