Existence of repeated elements II (sliding window, hash table)

Ricochet: Ricochet

        Given an array of integers nums and an integer k , check whether there are two different indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k . Returns true if present; otherwise, returns false.

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

hint:

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

Sample code 1: [sliding window + hash table]

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        s =  set()
        for i in range(len(nums)):
            if i > k:
                s.remove(nums[i-k-1])
            if nums[i] in s:
                return True
            s.add(nums[i])
        return False

Analysis of ideas:

 

Sample code 2: 【Hash】

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        #哈希表保存数字和相应的索引
        hash_ = {}
        for index, num in enumerate(nums):
            #如果数字已经存在于哈希表中了,就将现在的索引和之前的索引相减检查是否满足条件
            if num in hash_:
                if index - hash_[num] <= k:
                    return True
                #数字存在但是索引相减不满足条件,就更新这个数字的索引于最近的一项,保证再次遇到相同的数字能有最小的索引相减值
                hash_[num] = index
            #如果不存在这个数字,加入哈希表
            hash_[num] = index
        #如果循环结束了仍然没有满足条件的,则不存在这样的数字,返回False
        return False

Guess you like

Origin blog.csdn.net/weixin_44799217/article/details/131820581