Skip to content

219. Contains Duplicate II

难度: 简单

刷题内容

原题连接

  • https://leetcode.com/problems/contains-duplicate-ii/

内容描述

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 absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

解题方案

思路 1

这道题虽然看似简单,但是我还是经历几次失败

第一次我打算用最粗暴的方法来做,直接 Time Limit Exceeded,代码如下:

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

然后我打算用第 217 题的方法来一遍,还是报 Time Limit Exceeded 这个错,代码如下L:

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

终于我想到了用字典来存,这个元素还没出现过,就以 的形式存进字典里,如果 num 再次出现了,计算相邻距离,小于等于 k 则 return true,否则更新字典中元素的位置,

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        lookup = {}
        for i in range(len(nums)):
            if nums[i] not in lookup:
                lookup[nums[i]] = i
            else:
                if i - lookup[nums[i]] <= k:
                    return True
                else:
                    lookup[nums[i]] = i
        return False


回到顶部