首页 技术 正文
技术 2022年11月21日
0 收藏 612 点赞 3,596 浏览 1069 个字

题目:

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

欢迎关注微..信.公.众..号: 爱写Bug

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,954
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,479
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,291
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,108
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,740
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,774