leetcode python3 简单题219. Contains Duplicate II

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第二百一十九题

(1)题目
英文:

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.

中文:
给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的 绝对值 至多为 k。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/contains-duplicate-ii

(2)解法
使用哈希表
(耗时:64ms,内存:21.4M)

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

猜你喜欢

转载自blog.csdn.net/qq_37285386/article/details/106098179
今日推荐