TikTok 面试真题解析:最短好子数组长度(至少包含 k 个不同整数)|滑动窗口经典题

35次阅读
没有评论

For an array of n positive integers arr[n] and an integer k, a subarray is considered good if it consists of at least k distinct integers. Find the minimum length subarray that is good. If there is no such subarray, return -1.

Example:
arr = [2, 2, 1, 1, 3]
k = 3

The subarrays with at least k = 3 distinct integers are [2, 2, 1, 1, 3] and [2, 1, 1, 3]. Return 4, the minimum length of a good subarray.

Function Description
Complete the function findMinimumLengthSubarray in the editor below.

findMinimumLengthSubarray has the following parameter(s):

  • int arr[n]: the array to partition
  • int k: the number of distinct elements a good subarray must contain

Returns

  • int: the minimum length possible for a good subarray, or -1 if there is none

这道题要求在数组中找到一个最短的连续子数组,使其中“不同整数的个数”不少于 k。常见思路是使用滑动窗口:右指针不断扩展窗口、统计不同数字个数,当满足条件后尽量移动左指针缩小区间,从而得到最小长度。如果整个数组都无法满足条件,则返回 -1。

正文完
 0