题目I
python代码
1 暴力判断
def containsDuplicate(nums):
for i in range(len(nums) - 1):
if nums[i] in nums[i+1:]:
return True
return False
2 排序比较
def containsDuplicate(nums):
nums.sort()
for i in range(len(nums) - 1):
if nums[i] == nums[i+1]:
return True
return False
3 集合判断法
def containsDuplicate(nums):
if len(set(nums)) == len(nums):
return False
else:
return True
题目II
python 代码
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
dict={}
for i in range(len(nums)):
if(nums[i] not in dict):
dict[nums[i]]=i
else:
if(i-dict[nums[i]]<=k):
return True
else:
dict[nums[i]]=i
return False
题目III
python代码
1 逐个比较
def containsNearbyAlmostDuplicate(self,nums, k, t):
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if abs(j-i)<=k and abs(nums[i]-nums[j])<=t:
return True
return False
2 先分组再判断
def containsNearbyAlmostDuplicate(self, nums, k, t):
if t < 0 or k < 0:
return False
all_buckets = {}
bucket_size = t + 1 # 桶的大小设成t+1更加方便
for i in range(len(nums)):
bucket_num = nums[i] // bucket_size # 放入哪个桶
if bucket_num in all_buckets: # 桶中已经有元素了
return True
all_buckets[bucket_num] = nums[i] # 把nums[i]放入桶中
if (bucket_num - 1) in all_buckets and abs(all_buckets[bucket_num - 1] - nums[i]) <= t: # 检查前一个桶
return True
if (bucket_num + 1) in all_buckets and abs(all_buckets[bucket_num + 1] - nums[i]) <= t: # 检查后一个桶
return True
# 如果不构成返回条件,那么当i >= k 的时候就要删除旧桶了,以维持桶中的元素索引跟下一个i+1索引只差不超过k
if i >= k:
all_buckets.pop(nums[i-k]//bucket_size)
return False