Yingying

你必须非常努力,才能看起来毫不费力

219. Contains Duplicate II *

Given an array of integers and an integer k, find out whether there are two distinct indicesi and j in the array such that nums[i] = nums[j] and the difference betweeni and j is at most k.

My code:

Wrong (Time exceeded)

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        n = len(nums)
        dict ={}
        for i in range(n):
            if nums[i] in dict.keys():
                dict[nums[i]].append(i)
            else:
               dict[nums[i]]=[i]
        for key in dict.keys():
            keyLen= len(dict[key])
            for j in range(keyLen-1):
                if dict[key][j+1] - dict[key][j] <=k:
                    return True
        return False
                
Wrong (Time exceeded)
class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        n = len(nums)
        currentList=[]
        for i in range(n):
            if i > k:
                currentList.pop(0)
            if nums[i] in currentList:
                return True
            else:
                currentList.append(nums[i])
        return False

Accepted:

Reference

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        dic = {}
        for i, v in enumerate(nums):
            if v in dic and i - dic[v] <= k:
                return True
            dic[v] = i
        return False


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/alwaystry/article/details/52355917
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

219. Contains Duplicate II *

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭