LeetCode 题解工作台
将 x 减到 0 的最小操作数
给你一个整数数组 nums 和一个整数 x 。每一次操作时,你应当移除数组 nums 最左边或最右边的元素,然后从 x 中减去该元素的值。请注意,需要 修改 数组以供接下来的操作使用。 如果可以将 x 恰好 减到 0 ,返回 最小操作数 ;否则,返回 -1 。 示例 1: 输入: nums = [1…
5
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
根据题目描述,我们需要移除数组 左右两端的元素,使得移除的元素和等于 ,且移除的元素个数最少。我们可以将问题转化为:找到数组 中最长的连续子数组,使得子数组的和 $s = \sum_{i=0}^{n} nums[i] - x$。这样,我们就可以将问题转化为求解数组 中和为 的最长连续子数组的长度 ,答案即为 $n - mx$。 我们初始化 $mx = -1$,然后使用哈希表 来存储前缀和…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 nums 和一个整数 x 。每一次操作时,你应当移除数组 nums 最左边或最右边的元素,然后从 x 中减去该元素的值。请注意,需要 修改 数组以供接下来的操作使用。
如果可以将 x 恰好 减到 0 ,返回 最小操作数 ;否则,返回 -1 。
示例 1:
输入:nums = [1,1,4,2,3], x = 5 输出:2 解释:最佳解决方案是移除后两个元素,将 x 减到 0 。
示例 2:
输入:nums = [5,6,7,8,9], x = 4 输出:-1
示例 3:
输入:nums = [3,2,20,1,1,3], x = 10 输出:5 解释:最佳解决方案是移除后三个元素和前两个元素(总共 5 次操作),将 x 减到 0 。
提示:
1 <= nums.length <= 1051 <= nums[i] <= 1041 <= x <= 109
解题思路
方法一:哈希表 + 前缀和
根据题目描述,我们需要移除数组 左右两端的元素,使得移除的元素和等于 ,且移除的元素个数最少。我们可以将问题转化为:找到数组 中最长的连续子数组,使得子数组的和 。这样,我们就可以将问题转化为求解数组 中和为 的最长连续子数组的长度 ,答案即为 。
我们初始化 ,然后使用哈希表 来存储前缀和,键为前缀和,值为前缀和对应的下标。
遍历数组 ,对于当前元素 ,计算前缀和 ,如果 不在哈希表中,则将 加入哈希表;如果 在哈希表中,则更新 。
最后,如果 ,则返回 ,否则返回 。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def minOperations(self, nums: List[int], x: int) -> int:
s = sum(nums) - x
vis = {0: -1}
mx, t = -1, 0
for i, v in enumerate(nums):
t += v
if t not in vis:
vis[t] = i
if t - s in vis:
mx = max(mx, i - vis[t - s])
return -1 if mx == -1 else len(nums) - mx
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Understand how to efficiently find subarrays with a sum equal to a target value.
- question_mark
Can articulate the trade-offs between different sliding window techniques.
- question_mark
Demonstrates the ability to optimize solutions with binary search or hash-based lookups.
常见陷阱
外企场景- error
Failing to handle edge cases where no subarray can sum to x, leading to a return value of -1.
- error
Incorrectly managing the array's boundaries when adjusting the window, causing out-of-bound errors.
- error
Overcomplicating the solution with brute-force methods that result in suboptimal time complexity.
进阶变体
外企场景- arrow_right_alt
Modify the problem to find the minimum number of operations to reduce x to any given target.
- arrow_right_alt
Introduce constraints that prevent removal from both ends, restricting operations to one side of the array.
- arrow_right_alt
Extend the problem to handle negative numbers or floating point values in the array.