給定一個整數陣列和一個整數 k,判斷陣列中是否存在兩個不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的 絕對值 至多為 k,
示例 1:
輸入: nums = [1,2,3,1], k = 3
輸出: true
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
res = {}
for index, num in enumerate(nums):
if num in res and index-res[num] <=k:
return True
res[num] = index
return False
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/76779.html
標籤:其他
