关闭

219. Contains Duplicate II *

41人阅读 评论(0) 收藏 举报
分类:

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


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:44736次
    • 积分:3725
    • 等级:
    • 排名:第8629名
    • 原创:331篇
    • 转载:87篇
    • 译文:0篇
    • 评论:9条
    最新评论