LeetCode 题解工作台
元素值大于变化阈值的子数组
给你一个整数数组 nums 和一个整数 threshold 。 找到长度为 k 的 nums 子数组,满足数组中 每个 元素都 大于 threshold / k 。 请你返回满足要求的 任意 子数组的 大小 。如果没有这样的子数组,返回 -1 。 子数组 是数组中一段连续非空的元素序列。 示例 1:…
4
题型
4
代码语言
3
相关题
当前训练重点
困难 · 栈·状态
答案摘要
考虑从大到小遍历数组 中的每个元素 ,用并查集来维护以 作为子数组最小值的连通块。 遍历过程中:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路
题目描述
给你一个整数数组 nums 和一个整数 threshold 。
找到长度为 k 的 nums 子数组,满足数组中 每个 元素都 大于 threshold / k 。
请你返回满足要求的 任意 子数组的 大小 。如果没有这样的子数组,返回 -1 。
子数组 是数组中一段连续非空的元素序列。
示例 1:
输入:nums = [1,3,4,3,1], threshold = 6 输出:3 解释:子数组 [3,4,3] 大小为 3 ,每个元素都大于 6 / 3 = 2 。 注意这是唯一合法的子数组。
示例 2:
输入:nums = [6,5,6,5,8], threshold = 7 输出:1 解释:子数组 [8] 大小为 1 ,且 8 > 7 / 1 = 7 。所以返回 1 。 注意子数组 [6,5] 大小为 2 ,每个元素都大于 7 / 2 = 3.5 。 类似的,子数组 [6,5,6] ,[6,5,6,5] ,[6,5,6,5,8] 都是符合条件的子数组。 所以返回 2, 3, 4 和 5 都可以。
提示:
1 <= nums.length <= 1051 <= nums[i], threshold <= 109
解题思路
方法一:并查集
考虑从大到小遍历数组 中的每个元素 ,用并查集来维护以 作为子数组最小值的连通块。
遍历过程中:
在数组 中的下标为 ,若下标 对应的元素遍历过,可以将 与 进行合并,同理,若下标 对应的元素也遍历过了,将 与 合并。合并过程中更新连通块的大小。
作为当前连通块的最小值,当前连通块的大小为 ,若 ,说明找到了满足条件的子数组,返回 。
否则遍历结束,返回 。
时间复杂度 。
相似题目:
class Solution:
def validSubarraySize(self, nums: List[int], threshold: int) -> int:
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
def merge(a, b):
pa, pb = find(a), find(b)
if pa == pb:
return
p[pa] = pb
size[pb] += size[pa]
n = len(nums)
p = list(range(n))
size = [1] * n
arr = sorted(zip(nums, range(n)), reverse=True)
vis = [False] * n
for v, i in arr:
if i and vis[i - 1]:
merge(i, i - 1)
if i < n - 1 and vis[i + 1]:
merge(i, i + 1)
if v > threshold // size[find(i)]:
return size[find(i)]
vis[i] = True
return -1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate effectively utilizes stack-based state management to track valid subarrays.
- question_mark
Candidate suggests a sliding window to avoid redundant checks and improve efficiency.
- question_mark
Candidate demonstrates an understanding of binary search for optimization of subarray length checks.
常见陷阱
外企场景- error
Incorrectly managing the sliding window or stack, leading to incorrect subarray evaluations.
- error
Failing to account for edge cases like the smallest or largest subarray sizes.
- error
Overlooking the need for an efficient solution, potentially resulting in a time complexity of O(n^2).
进阶变体
外企场景- arrow_right_alt
Changing the condition for valid subarrays (e.g., using a different mathematical relationship for the elements).
- arrow_right_alt
Restricting the array to smaller or larger sizes, affecting the stack or sliding window management.
- arrow_right_alt
Including additional constraints like negative numbers or specific ranges for elements.