LeetCode Minimum Size Subarray Sum

本文探讨了如何在给定数组和目标和的情况下,找出能达到该和的最小子数组长度。通过双指针技巧实现O(n)复杂度的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead.

For example, given the array [2,3,1,2,4,3] and s = 7,
the subarray [4,3] has the minimal length under the problem constraint.

click to show more practice.

More practice:

If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

题意:

给定一个数组和一个目标的和,然后在这个数组中求能达到这个和的最小的子数组的长度。

题解:

一开始LZ理解错了,以为可以将原来的数组重排列的,但是后来经过具体数据的验证,发现不能改变原来的数组,那么就只能老老实实地从头到尾来一步步地加,一步步地逼近结果。考虑两个指针,left和right,分别记录的是子数组的左右的边界;一开始让right右移,直到子数组的和大于或等于给定的值或者是right达到数组末尾,此时我们更新最短距离,同时这个更新我们放在下一个循环中,也就是考虑将left右移一位,然后再在sum中减去原来的值,不停地重复上面的过程,直到right到达末尾为止,且left也到达临界位置。

public class Solution 
{
    public static int minSubArrayLen(int s,int[] nums)
	{
		if(nums == null || nums.length == 0)
			return 0;
		int left = 0,right = 0,sum = 0,length = nums.length,res = length + 1;
		while(right < length)
		{
			while(sum < s && right < length)
			{
				sum += nums[right++];
			}
			while(sum >= s)
			{
				res = Math.min(res, right - left);   //这个是用来维护最短距离的
				sum -= nums[left++];     //同时这里每次都是减一个数
			} 
		}
		return res == length + 1 ? 0 : res;   //同时,这里是用来返回具体的距离的
<span style="font-family: Arial, Helvetica, sans-serif;">}</span>
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值