給定一個整數數組和一個整數 k,判斷數組中是否存在兩個不一樣的索引 i 和 j,使得 nums [i] = nums [j],而且 i 和 j 的差的絕對值最大爲 k。java
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.python
示例 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] 相等的元素code
能夠優化的地方只有維護的滑動窗口這一部分, 下降在這個動態數組中查找操做的時間複雜度索引
優化一個數組內的查找時間複雜度的方法很是多:rem
秦策只有用哈希集合維護滑動窗口才不會超時hash
Java:io
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