219. Contains Duplicate II [easy] (Python)

博客介绍了LeetCode的第219题,题目要求在给定数组中找到差值不超过k的重复元素。文章提供了两种Python解题思路,包括使用字典记录元素下标和维护一个包含最近k个元素的集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

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

题目翻译

给定一个数组,和一个整数k,判断该数组中是否存在不同下标的 i 和 j 两个元素,使得 nums[i] = nums[j],且 i 和 j 的差不超过k。

思路方法

暴力两重循环不可取,无法AC。。。

思路一

遍历所有元素,将元素值当做键、元素下标当做值,存放在一个字典中。遍历的时候,如果发现重复元素,则比较其下标的差值是否小于k,如果小于则可直接返回True,否则更新字典中该键的值为新的下标。

代码

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

思路二

在遍历列表的时候维护一个集合,集合中保存当前元素前面的k个元素,每次访问一个元素时判断是否在该集合中出现过。

代码

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        window = set([])
        for i in xrange(len(nums)):
            if i > k:
                window.discard(nums[i-k-1])
            if nums[i] in window:
                return True
            else:
                window.add(nums[i])
        return False

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51674266

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值