您的位置:首页 > 大数据 > 人工智能

【leetcode题解】【99.38】【E】Contains Duplicate II

2015-12-17 19:28 204 查看
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 difference
between i and j is at most k.

Subscribe to see which companies asked this question

维持一个k大小的滑动窗口,需要考虑的就是边界问题,略麻烦。

判断窗口k里面是否有重复元素,可以利用集合,看看“集合化”之后,大小是否发生变化。

竟然跑出了击败99.38的速度,可见并不是很笨。

class Solution(object):
def containsNearbyDuplicate(self, nums, k):
if not nums:
return 0 < k
if len(nums) == 1 or k == 0:
return False
if len(nums) <= k:
s = set(nums)
return len(s) < len(nums)

i = 0
while i < len(nums)-k:
t = nums[i:i+k+1]
i += 1

s = set(t)
if len(s) < len(t):
return True

return False
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: