发布于2021-03-13 14:14 阅读(1452) 评论(0) 点赞(28) 收藏(3)
https://binarysearch.com/problems/Number-of-Operations-to-Decrement-Target-to-Zero
题目要求去除数组nums的左右两端元素,并且去除的元素和为target,也就是留下中间的子数组,其和为sum(nums) - target;
题目还要求去除的元素个数越小越好,也就是留下的中间子数组的长度越大越好;
那么问题就转化为了找数组中间和为sum(nums) - target的最长子数组,令该和为我们的新目标new_target,步骤如下:
class Solution:
def solve(self, nums, target):
new_target = sum(nums) - target
if new_target == 0:
return len(nums)
tmp_sum = 0
max_len = 0
left = 0
for right, num in enumerate(nums):
tmp_sum += num
while tmp_sum >= new_target and left <= right:
if tmp_sum == new_target:
max_len = max(max_len, right - left + 1)
tmp_sum -= nums[left]
left += 1
return len(nums) - max_len if max_len else -1
import java.util.*;
class Solution {
public int solve(int[] nums, int target) {
int n = nums.length;
int newTarget = Arrays.stream(nums).sum() - target;
if(newTarget == 0) return n;
int left = 0, tmpSum = 0, maxLen = 0;
for(int right = 0; right < n; right++){
tmpSum += nums[right];
while(tmpSum >= newTarget && left <= right){
if(tmpSum == newTarget){
maxLen = Math.max(maxLen, right - left + 1);
}
tmpSum -= nums[left];
left++;
}
}
return maxLen == 0 ? -1 : n - maxLen;
}
}
原文链接:https://blog.csdn.net/qq_41726606/article/details/114663700
作者:Hdhhd
链接:http://www.javaheidong.com/blog/article/114437/dfc71d77b9829575f1bf/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!