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]has3different integers:1,2, and3.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1,2,1,2,3], k = 2 Output: 7 Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]
Example 2:
Input: nums = [1,2,1,3,4], k = 3 Output: 3 Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].
Constraints:
1 <= nums.length <= 2 * 10^41 <= nums[i], k <= nums.length
题目链接:https://leetcode.com/problems/subarrays-with-k-different-integers/
题目大意:求恰好有k个不同数字的区间个数
题目分析:恰好有k个不好求,但至多有k个则非常容易,恰好k个=至多k个-至多k-1个,至多有k个可以用滑动窗,用hash判断每个数字出现的次数,并用一个值记录当前有多少个不同的数字
13ms,时间击败88.84%
class Solution {
public int subarraysWithKDistinct(int[] nums, int k) {
return atMostK(nums, k) - atMostK(nums, k - 1);
}
public int atMostK(int[] nums, int k) {
int[] cnt = new int[20001];
int diff = 0, ans = 0, n = nums.length, i = 0;
for (int j = 0; j < n; j++) {
if (cnt[nums[j]] == 0) {
diff++;
}
cnt[nums[j]]++;
while (diff > k) {
cnt[nums[i]]--;
if (cnt[nums[i]] == 0) {
diff--;
}
i++;
}
if (diff <= k) {
ans += j - i;
}
}
return ans;
}
}

该博客主要介绍了如何解决LeetCode上的一个题目,即找到数组中恰好包含k个不同整数的子数组个数。作者使用了滑动窗口和哈希映射的方法,通过维护窗口内不同整数的数量,实现了高效地计算。文章详细解析了算法思路,包括如何利用滑动窗口减少重复计算和哈希映射统计不同整数的出现次数。
2349

被折叠的 条评论
为什么被折叠?



