LeetCode 题解工作台

将 x 减到 0 的最小操作数

给你一个整数数组 nums 和一个整数 x 。每一次操作时,你应当移除数组 nums 最左边或最右边的元素,然后从 x 中减去该元素的值。请注意,需要 修改 数组以供接下来的操作使用。 如果可以将 x 恰好 减到 0 ,返回 最小操作数 ;否则,返回 -1 。 示例 1: 输入: nums = [1…

category

5

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

根据题目描述,我们需要移除数组 左右两端的元素,使得移除的元素和等于 ,且移除的元素个数最少。我们可以将问题转化为:找到数组 中最长的连续子数组,使得子数组的和 $s = \sum_{i=0}^{n} nums[i] - x$。这样,我们就可以将问题转化为求解数组 中和为 的最长连续子数组的长度 ,答案即为 $n - mx$。 我们初始化 $mx = -1$,然后使用哈希表 来存储前缀和…

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 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 <= 105
  • 1 <= nums[i] <= 104
  • 1 <= x <= 109
lightbulb

解题思路

方法一:哈希表 + 前缀和

根据题目描述,我们需要移除数组 numsnums 左右两端的元素,使得移除的元素和等于 xx,且移除的元素个数最少。我们可以将问题转化为:找到数组 numsnums 中最长的连续子数组,使得子数组的和 s=i=0nnums[i]xs = \sum_{i=0}^{n} nums[i] - x。这样,我们就可以将问题转化为求解数组 numsnums 中和为 ss 的最长连续子数组的长度 mxmx,答案即为 nmxn - mx

我们初始化 mx=1mx = -1,然后使用哈希表 visvis 来存储前缀和,键为前缀和,值为前缀和对应的下标。

遍历数组 numsnums,对于当前元素 nums[i]nums[i],计算前缀和 tt,如果 tt 不在哈希表中,则将 tt 加入哈希表;如果 tst - s 在哈希表中,则更新 mx=max(mx,ivis[ts])mx = \max(mx, i - vis[t - s])

最后,如果 mx=1mx = -1,则返回 1-1,否则返回 nmxn - mx

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组 numsnums 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

将 x 减到 0 的最小操作数题解:数组·哈希·扫描 | LeetCode #1658 中等