天天看點

LeetCode 219: 存在重複元素 II Contains Duplicate II

題目:

​ 給定一個整數數組和一個整數 k,判斷數組中是否存在兩個不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的絕對值最大為 k。

​ 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.

示例 1:

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

示例 2:

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

示例 3:

輸入: nums = [1,2,3,1,2,3], k = 2
輸出: false           

解題思路:

​ 周遊數組, 維護一個大小為 K 的滑動視窗, 該視窗周遊到的第 i 個元素, 後 K 個元素組成的數組

nums[ i, i + K]

,查找該數組内是否有與 nums[i] 相等的元素

​ 可以優化的地方隻有維護的滑動視窗這一部分, 降低在這個動态數組中查找操作的時間複雜度

優化一個數組内的查找時間複雜度的方法非常多:

  • 暴力破解: 直接操作指針将正在周遊的元素與其之後 K 個元素的節對比
  • 平衡二叉樹: 建構一個平衡二叉樹維護這個滑動視窗
  • 哈希集合: 維護一個長度為 K 的哈希集合,查找複雜度為 O(1)

秦策隻有用哈希集合維護滑動視窗才不會逾時

HashSet解題:

​ Java:

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        HashSet<Integer> set=new HashSet<>();
        for(int i=0;i<nums.length;i++){
            if(set.contains(nums[i])) return true;
            set.add(nums[i]);
            if(set.size()>k) set.remove(nums[i - k]);
        }
        return false;
    }
}           

Python:

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

歡迎關注微..信.公.衆..号: 愛寫Bug

繼續閱讀