Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
1. 暴力解法 O(n^2), 超时
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] == nums[j] and abs(i-j) <= k:
return True
return False
2. Hashmap
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
charmap = {}
for i in range(len(nums)):
if nums[i] in charmap and abs(i-charmap[nums[i]]) <= k:
return True
else:
charmap[nums[i]] = i
return False