文章目录
1、题目描述
给你一个整数数组 nums 和一个整数 k ,判断数组中是否存在两个 不同的索引 i 和 j ,满足 nums[i] == nums[j] 且 abs(i - j) <= k 。如果存在,返回 true ;否则,返回 false 。
2、思路1
暴力法,直接两层for循环,但会超时。
代码
python
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
# 暴力会超时
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i] != nums[j]:
continue
else:
res = abs(i - j) <= k
if res is True:
return True
return False
3、思路2
借助哈希表,来不断的存储元素值以及下标,若当前元素已经在字典里,则取出对应下标与k进行比较;若不满足条件,则将当前遍历的元素的下标存入字典,覆盖掉原来的下标。
代码
python
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
# 哈希表
from collections import defaultdict
hash_map = defaultdict(int)
for i in range(len(nums)):
# 若当前元素不在哈希表,则存进去
if nums[i] not in hash_map:
hash_map[nums[i]] = i
# 若在哈希表里:
else:
res = abs(i - hash_map[nums[i]]) <= k
# 若查找成功,则返回True
if res is True:
return True
else:
hash_map[nums[i]] = i # 覆盖字典为最新的下标
return False