K 个不同整数的子数组
给定一个正整数数组 nums和一个整数k,返回num中「好子数组」的数目。
如果 nums 的某个子数组中不同整数的个数恰好为 k,则称 nums 的这个连续、不一定不同的子数组为 「好子数组 」。
例如,[1,2,3,1,2] 中有 3 个不同的整数:1,2,以及 3。
子数组是数组的连续部分。
示例 1:
输入:nums = [1,2,1,2,3], k = 2
输出:7
解释:恰好由 2 个不同整数组成的子数组:[1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].
示例 2:
输入:nums = [1,2,1,3,4], k = 3
输出:3
解释:恰好由 3 个不同整数组成的子数组:[1,2,1,3], [2,1,3], [1,3,4].
提示:
1 <= nums.length <= 2 * 104
1 <= nums[i], k <= nums.length
public class TestSolution { public static void main(String[] args) { int[] nums = {1, 2, 1, 3, 4}; int k = 3; System.out.println(subarraysWithKDistinct(nums, k)); System.out.println(subarraysWithKDistinct_(nums, k)); } public static int subarraysWithKDistinct(int[] nums, int k) { int count = 0; int right = 0; Set<Integer> set = new HashSet<>(); for (int i = 0; i < nums.length; ) { set.add(nums[right]); int size = set.size(); if (size < k) { right++; } else if (size == k) { count++; right++; } else { i++; set.clear(); right = i; } if (right >= nums.length) { i++; set.clear(); right = i; } } return count; } public static int subarraysWithKDistinct_(int[] nums, int k) { //恰好为K可以变为 最多为k个减去最多为k - 1个 return helper(nums, k) - helper(nums, k - 1); } private static int helper(int[] a, int k) { int n = a.length, left = 0, right = 0; int[] cnt = new int[n + 1]; int count = 0, res = 0; while (right < n) { if (cnt[a[right]] == 0) { count++; } cnt[a[right++]]++; while (count > k) { if (cnt[a[left]] == 1) { count--; } cnt[a[left++]]--; } res += right - left; } return res; } }
https://leetcode.cn/problems/subarrays-with-k-different-integers

浙公网安备 33010602011771号