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

  • 2019 年 11 月 10 日
  • 筆記

題目:

給定一個整數數組和一個整數 k,判斷數組中是否存在兩個不同的索引 ij,使得 nums [i] = nums [j],並且 ij 的差的絕對值最大為 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])