219. Contains Duplicate II(easy)
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.
Example 1:
Input: nums = [1,2,3,1], k = 3 Output: trueExample 2:
Input: nums = [1,0,1,1], k = 1 Output: trueExample 3:
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
这道题玩死我了Or2......
题意:是否存在2个相同的数字,下标距离《=k,只要存在就可以返回true了
1 count计数
so,先筛选出来有重复的数字,只在重复数字里考虑。
遍历nums,确认该数字在后面也有重复,计算下标距离
class Solution:
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
count = collections.Counter(nums)
s = [k for k,count in count.items() if count > 1]
for i in range(len(nums)):
if count[nums[i]] > 1:
index = nums[i+1:].index(nums[i])
if index+1 <= k:return True
count[nums[i]] -= 1
return False
2记录一个discussion里的比较容易懂的
使用字典,每次覆盖最新的位置下标
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
d = {}
for i,num in enumerate(nums):
if num in d:
if i - d[num] <= k:
return True
d[num] = i
return False