Skip to content

Latest commit

 

History

History
46 lines (32 loc) · 1.01 KB

0219. Contains Duplicate II.md

File metadata and controls

46 lines (32 loc) · 1.01 KB

题目

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

我的思路

这题和上一题一样,不同的是需要记录一下元素的位置,再遇到相同元素时先对两个下标进行比较。

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        dic={}
        for i in range(len(nums)):
            if nums[i] not in dic.keys():
                dic[nums[i]] = i
            else:
                if i - dic[nums[i]] <= k:
                    return True
                else:dic[nums[i]] = i
                
        return False