leetcode-219-存在重复元素②

题目描述:

leetcode-219-存在重复元素②

 

 第一次提交:超时

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        for i in range(len(nums)-1):
            for j in range(i+1,min(i+k+1,len(nums))):           
                if nums[i] == nums[j]:return True
        return False

第二次提交:超时

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        if k>=len(nums):
            if len(set(nums))!=len(nums):
                return True
        else:
            for i in range(len(nums)-k):
                if len(set(nums[i:i+k+1]))!=len(nums[i:i+k+1]):return True
        return False

优化:哈希表维护滑动窗口:O(N)

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        windows = set()
        for i in range(len(nums)):
            if nums[i] in windows:
                return True
            windows.add(nums[i])
            if len(windows) > k:
                windows.remove(nums[i-k])
        return False

 

上一篇:219. 存在重复元素 II - 力扣(LeetCode)


下一篇:普通211研究生大数据开发的秋招总结