力扣(LeetCode)1658. 将 x 减到 0 的最小操作数(C++/Python)

题目描述

pp

逆向思维+滑动窗口

题目分析 : 从数组左侧和右侧,取出左侧的连续数字,右侧的连续数字,使得这些数字之和等于 x,维护最小取数次数,作为答案 。

设整个数组之和 total ,除去左侧和右侧的连续数字,剩下的数组之和等于total-x ,而且剩下的数组正好是中间的连续数字。问题转化为,求数组之和等于total-x的最长连续数组。中间剩下的数组越长,左侧和右侧使用的数组就越短。

c++

class Solution {
public:
    int minOperations(vector<int>& nums, int x) {
        int target = accumulate(nums.begin(),nums.end(),0) - x;
        if(target<0) return -1;
        int ans = -1, l = 0, r = 0 , sum = 0;
        while(r<nums.size()){
            sum += nums[r++];
            while(sum>target) sum -= nums[l++];
            if(sum==target) ans = max(r-l,ans);
        }
        return ans<0?-1:nums.size()-ans;
    }
};

python3

class Solution:
    def minOperations(self, nums: List[int], x: int) -> int:
        target = sum(nums) - x
        if target < 0:
            return -1
        ans = -1
        l = r = s = 0
        while r < len(nums):
            s += nums[r]
            r += 1
            while s > target:
                s -= nums[l]
                l += 1
            if s == target:
                ans = max(ans, r - l)
        return ans if ans < 0 else len(nums) - ans
  1. 时间复杂度 : O ( n ) O(n) O(n) n n n 是数组长度 ,计算target ,维护滑动窗口的时间复杂度 O ( n ) O(n) O(n)
  2. 空间复杂度 : O ( 1 ) O(1) O(1) , 只使用常量级空间 。
AC

AC

致语
  • 理解思路很重要
  • 读者有问题请留言,清墨看到就会回复的。
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清墨韵染

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值