【Leetcode_总结】 219. 存在重复元素 II -python

Q:

219. 存在重复元素 II


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

示例 1:

输入: nums = [1,2,3,1], k = 3
输出: true

示例 2:

输入: nums = [1,0,1,1], k = 1
输出: true

思路: 如果没有重复元素,返回False,如果 K > len(nums) 且里面有重复元素,返回ture

剩下的就是暴力求解,遍历一下,代码如下:

class Solution:
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        
        if len(list(set(nums))) == len(nums):
            return False
        left = 0
        right = left + k
        if k >= len(nums):
            return len(list(set(nums))) < len(nums)
        while right < len(nums):
            while left < right:
                if nums[left] == nums[right]:
                    return True
                else:
                    right -= 1
            left += 1
            right = left + k
        if len(list(set(nums[left:]))) < len(nums[left:]):
            return True
        return False

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值