给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的 绝对值 至多为 k。
示例 1:
输入: nums = [1,2,3,1], k = 3
输出: true
示例 2:
输入: nums = [1,0,1,1], k = 1
输出: true
示例 3:
输入: nums = [1,2,3,1,2,3], k = 2
输出: false
1. 从上面的测试用例可以看出来,效率是关键,逻辑不复杂
2. 可以用dict来替代list改进效率,list.count是非常耗时的,
3. 那么思路就是
3.1 将 值:索引 构成一个字典
3.2 取得一个值,判断是否在字典中,不在就放进去
3.3 如果在,那么比较现在的索引和之前的索引(也就是值的value,因为只有一个)
3.4 如果不超过k就是好的,结束了,如果超过k,那么就要继续
3.5 如果继续,要更新字典的信息(你要用新的值-索引来比较了)
class Solution:
def containsNearbyDuplicate(self, nums: list, k: int) -> bool:
dict_nums = {}
for index_nums,value_nums in enumerate(nums):
if value_nums not in dict_nums:
dict_nums[value_nums]=index_nums
else:
kk = index_nums - dict_nums[value_nums]
if kk<=k:
return True
else:
dict_nums[value_nums]=index_nums
else:
return False