当前位置:网站首页>【滑动窗口】leetcode992. Subarrays with K Different Integers
【滑动窗口】leetcode992. Subarrays with K Different Integers
2022-06-23 00:33:00 【暮色_年华】
992. Subarrays with K Different Integers
Given an integer array nums and an integer k, return the number of good subarrays of nums.
A good array is an array where the number of different integers in that array is exactly k.
For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.
A subarray is a contiguous(连续的) part of an array.
题意:求连续子数组中数个数为k的区间总数
思路:滑动窗口

首先,可以枚举区间的右端点,求出每个右端点的区间个数后相加就是结果。
设j1是区间[j1,i]中数的种类为k的最左边的端点。
设j2是区间[j2,i]中数的种类为k-1的最左边的端点。
那么符号条件的区间就是j2-j1。
(特判:当j走到0,区间中数的种类数还是小于k时,此时j1j2重合j2-j1为0,符合题意)
可以证明,当i向右走时,j不能往回走,所以可以使用滑动窗口求解。
使用哈希表记录,区间中数的种类。哈希表的增删改查为o(1)
时间复杂度O(N)。
class Solution {
public int subarraysWithKDistinct(int[] nums, int k) {
Map<Integer,Integer>S1=new HashMap<>();
Map<Integer,Integer>S2=new HashMap<>();
int res=0;
for(int i=0,j1=0,j2=0,cnt1=0,cnt2=0;i<nums.length;i++){
if(S1.getOrDefault(nums[i],0)==0)cnt1++;
S1.put(nums[i],S1.getOrDefault(nums[i],0)+1);
while(cnt1>k){
S1.put(nums[j1],S1.getOrDefault(nums[j1],0)-1);
if(S1.get(nums[j1])==0)cnt1--;
j1++;
}
if(S2.getOrDefault(nums[i],0)==0)cnt2++;
S2.put(nums[i],S2.getOrDefault(nums[i],0)+1);
while(cnt2>=k){
S2.put(nums[j2],S2.getOrDefault(nums[j2],0)-1);
if(S2.get(nums[j2])==0)cnt2--;
j2++;
}
res+=j2-j1;
}
return res;
}
}边栏推荐
- 在一条DML语句中插入/更新/删除/获取几百万行数据,你会特别注意什么?
- Sword finger offer 11 Minimum number of rotation array
- 事物系统的几种异常场景
- RedisTemplate使用遇到\x00的問題
- Oracle ASM使用asmcmd中的cp命令来执行远程复制
- Typecho仿盧松松博客主題模板/科技資訊博客主題模板
- Eslint simple configuration
- Kunlun distributed database sequence function and its implementation mechanism
- 07 项目成本管理
- [arm] it is reported that horizontal display is set for LVDS screen of rk3568 development board
猜你喜欢

关于测试/开发程序员技术的一些思考,水平很高超的,混不下去了......

Kunlundb query optimization (I)

2022 TIANTI match - National Finals rematch

KunlunDB查询优化(二)Project和Filter下推

C sqlsugar, hisql, FreeSQL ORM framework all-round performance test vs. sqlserver performance test

Binary tree to string and string to binary tree

Optimization - linear programming

KunlunDB查询优化(三)排序下推

再立云计算“昆仑”,联想混合云Lenovo xCloud凭什么?

Redis缓存
随机推荐
Several abnormal scenarios of things system
【首发】请求一下子太多了,数据库危
MySQL-Seconds_behind_master 的精度误差
EasyCVR使用RTMP推流时不显示界面如何解决?
Good things to share
【GO】Go数组和切片(动态数组)
Web Caching Technology
Some thoughts about the technology of test / development programmers are very advanced, and they can't go on
Es5 object extension methods //call, apply and bind
OJ daily practice - sorting and naming
华为云招募工业智能领域合作伙伴,强力扶持+商业变现
Eslint simple configuration
关于测试/开发程序员技术的一些思考,水平很高超的,混不下去了......
数据库每日一题---第20天:按日期分组销售产品
DCC888 :SSA (static single assignment form)
TiDB VS MySQL
昆仑分布式数据库技术优势
Kunlun distributed database technology advantages
详解openGauss多线程架构启动过程
Kunlundb backup and recovery