ZhangZhihui's Blog  

Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= 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

 

Constraints:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • 0 <= k <= 105

 

My Solution:

from collections import Counter

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """

        if k == 0:
            return False

        counter = Counter(nums)
        if len(counter) == len(nums):
            return False

        counter_gt1 = {num: count for (num, count) in counter.items() if count > 1}
        for num in counter_gt1:
            cnt = counter_gt1[num]
            idx1 = nums.index(num)
            while cnt > 1:
                idx2 = nums[idx1 + 1:].index(num) + idx1 + 1
                if idx2 - idx1 <= k:
                    return True
                else:
                    idx1 = idx2
                    cnt -= 1
        
        return False

 

 

posted on 2025-03-17 20:04  ZhangZhihuiAAA  阅读(7)  评论(0)    收藏  举报