LeetCode 题解工作台
长度最小的子数组
给定一个含有 n 个正整数的数组和一个正整数 target 。 找出该数组中满足其总和大于等于 target 的长度最小的 子数组 [nums l , nums l+1 , ..., nums r-1 , nums r ] ,并返回其长度 。 如果不存在符合条件的子数组,返回 0 。 示例 1: 输…
4
题型
7
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
我们先预处理出数组 的前缀和数组 ,其中 表示数组 前 项元素之和。由于数组 中的元素都是正整数,因此数组 也是单调递增的。另外,我们初始化答案 $ans = n + 1$,其中 为数组 的长度。 接下来,我们遍历前缀和数组 ,对于其中的每个元素 ,我们可以通过二分查找的方法找到满足 $s[j] \geq s[i] + target$ 的最小下标 ,如果 $j \leq n$,则说…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其总和大于等于 target 的长度最小的 子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
示例 1:
输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
示例 2:
输入:target = 4, nums = [1,4,4] 输出:1
示例 3:
输入:target = 11, nums = [1,1,1,1,1,1,1,1] 输出:0
提示:
1 <= target <= 1091 <= nums.length <= 1051 <= nums[i] <= 104
进阶:
- 如果你已经实现
O(n)时间复杂度的解法, 请尝试设计一个O(n log(n))时间复杂度的解法。
解题思路
方法一:前缀和 + 二分查找
我们先预处理出数组 的前缀和数组 ,其中 表示数组 前 项元素之和。由于数组 中的元素都是正整数,因此数组 也是单调递增的。另外,我们初始化答案 ,其中 为数组 的长度。
接下来,我们遍历前缀和数组 ,对于其中的每个元素 ,我们可以通过二分查找的方法找到满足 的最小下标 ,如果 ,则说明存在满足条件的子数组,我们可以更新答案,即 。
最后,如果 ,则说明存在满足条件的子数组,返回 ,否则返回 。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
n = len(nums)
s = list(accumulate(nums, initial=0))
ans = n + 1
for i, x in enumerate(s):
j = bisect_left(s, x + target)
if j <= n:
ans = min(ans, j - i)
return ans if ans <= n else 0
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates a solid understanding of sliding window techniques and can apply them to optimize the subarray sum problem.
- question_mark
The candidate is familiar with binary search and can leverage it effectively for narrowing the search space.
- question_mark
The candidate integrates prefix sums into their solution, showing they can optimize repetitive sum calculations.
常见陷阱
外企场景- error
Overcomplicating the problem by trying to solve it without leveraging the sliding window or binary search techniques.
- error
Failing to consider edge cases where no subarray satisfies the sum condition, leading to incorrect answers like returning a subarray length of zero when it should be zero.
- error
Using brute force approaches that result in a time complexity of O(n^2) or worse, rather than utilizing O(n) algorithms.
进阶变体
外企场景- arrow_right_alt
Allowing negative numbers in the input array and adjusting the solution accordingly.
- arrow_right_alt
Modifying the problem to return the subarray itself, not just its length.
- arrow_right_alt
Changing the sum condition to be less than or equal to the target instead of greater than or equal to.