219. 存在重复元素 II

 

前两个超时,第三个用的set过了。

代码一:

 1 class Solution(object):
 2     def containsNearbyDuplicate(self, nums, k):
 3         """
 4         :type nums: List[int]
 5         :type k: int
 6         :rtype: bool
 7         """
 8         for i in range(len(nums)):
 9             for j in range(i + 1, i + k + 1):
10                 if j < len(nums) and nums[i] == nums[j]:
11                     return True
12         return False

代码二:

 1 class Solution(object):
 2     def containsNearbyDuplicate(self, nums, k):
 3         """
 4         :type nums: List[int]
 5         :type k: int
 6         :rtype: bool
 7         """
 8         i = 0
 9         j = i + 1
10         while i < len(nums) and j < len(nums):
11             for index in range(j, j + k):
12                 if index < len(nums) and nums[index] == nums[i]:
13                     return True
14             i += 1
15             j = i + 1
16         return False

代码三:

1 class Solution(object):
2     def containsNearbyDuplicate3(self, nums, k):
3         arr = {}
4         for i in range(len(nums)):
5             if nums[i] in arr and i - arr[nums[i]] <= k:
6                 return True
7             arr[nums[i]] = i
8         return False
原文地址:https://www.cnblogs.com/panweiwei/p/12757584.html