给定一个整数数组和一个整数 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