Leetcode 219. 存在重复元素(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.

Example1:

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

Example2:

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

Example3:

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

思路

将元素作为key,索引作为value存入字典里,遇到已经存在的key就检查i和j之间的差值是否小于k

Code

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        d = {}
        for i in range(len(nums)):
            num = nums[i]
            # check whether num has been added into dict
            if num in d:
                # if difference of i and the last index of num is within k, then find it
                if i - d[num] <= k:
                    return True
                d[num] = i
            d[num] = i
        return False

猜你喜欢

转载自www.cnblogs.com/yufeng97/p/12593725.html