zoukankan      html  css  js  c++  java
  • Leetcode 219. 存在重复元素 II (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

    思路

    将元素作为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
    
  • 相关阅读:
    java内部类
    unityUI拖拽
    Java泛型
    java集合
    python爬取糗百段子
    python读取文件并保存到mysql数据库
    BeanShell Sampler 身份证号-jmeter
    python操作数据库
    创建身份证号
    随机生成四要素
  • 原文地址:https://www.cnblogs.com/yufeng97/p/12593725.html
Copyright © 2011-2022 走看看