zoukankan      html  css  js  c++  java
  • [LeetCode] 1658. Minimum Operations to Reduce X to Zero

    You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.

    Return the minimum number of operations to reduce x to exactly 0 if it's possible, otherwise, return -1.

    Example 1:

    Input: nums = [1,1,4,2,3], x = 5
    Output: 2
    Explanation: The optimal solution is to remove the last two elements to reduce x to zero.
    

    Example 2:

    Input: nums = [5,6,7,8,9], x = 4
    Output: -1
    

    Example 3:

    Input: nums = [3,2,20,1,1,3], x = 10
    Output: 5
    Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.

    Constraints:

    • 1 <= nums.length <= 105
    • 1 <= nums[i] <= 104
    • 1 <= x <= 109

    将 x 减到 0 的最小操作数。

    给你一个整数数组 nums 和一个整数 x 。每一次操作时,你应当移除数组 nums 最左边或最右边的元素,然后从 x 中减去该元素的值。请注意,需要 修改 数组以供接下来的操作使用。

    如果可以将 x 恰好 减到 0 ,返回 最小操作数 ;否则,返回 -1 。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/minimum-operations-to-reduce-x-to-zero
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    思路是前缀和。首先我们处理一下目标值x,因为题目问的其实是数组中间的某个子数组,满足其数组和 = 数组全部数字的和 - 两边某一些数字,所以我们先把目标值定为 -x,这样当我们用前缀和的思路找到一个符合要求的子数组的时候,这个子数组已经等于数组所有数字的和 - x了。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public int minOperations(int[] nums, int x) {
     3         int target = -x;
     4         int len = nums.length;
     5         for (int num : nums) {
     6             target += num;
     7         }
     8         // corner case
     9         if (target == 0) {
    10             return len;
    11         }
    12         // normal case
    13         int res = Integer.MIN_VALUE;
    14         int sum = 0;
    15         HashMap<Integer, Integer> map = new HashMap<>();
    16         map.put(0, -1);
    17         for (int i = 0; i < len; i++) {
    18             sum += nums[i];
    19             if (map.containsKey(sum - target)) {
    20                 res = Math.max(res, i - map.get(sum - target));
    21             }
    22             map.put(sum, i);
    23         }
    24         return res == Integer.MIN_VALUE ? -1 : len - res;
    25     }
    26 }

    LeetCode 题目总结 

  • 相关阅读:
    第二十一回  基础才是重中之重~网站bin目录下的程序集自动加载
    C# Socket编程(4)初识Socket和数据流
    SQL日期格式转换(备忘)
    C#正则表达式匹配替换字符串
    CSS万能闭合标签(常用)
    JS比较两个时间大小的简洁代码
    List的Sort自定义排序实例
    char(n) varchar(n)的区别
    AJAX小例一枚(仅GET)
    聚合不应出现在 WHERE 子句中,除非该聚合位于 HAVING 子句或选择列表所包含
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14284844.html
Copyright © 2011-2022 走看看