简体   繁体   English

最小尺寸子阵列

[英]Minimum size subarray

https://www.programcreek.com/2014/05/leetcode-minimum-size-subarray-sum-java/ https://www.programcreek.com/2014/05/leetcode-minimum-size-subarray-sum-java/

I do not understand how this code works.我不明白这段代码是如何工作的。 As stated in the challenge the purpose is to正如挑战中所述,目的是

Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s.给定一个由 n 个正整数和一个正整数 s 组成的数组,求其总和 ≥ s 的子数组的最小长度。 If there isn't one, return 0 instead.如果没有,则返回 0。

Here is the code:这是代码:

public int minSubArrayLen(int s, int[] nums) {
if(nums==null || nums.length==1)
    return 0;

int result = nums.length;

int start=0;
int sum=0;
int i=0;
boolean exists = false;

while(i<=nums.length){
    if(sum>=s){
        exists=true; //mark if there exists such a subarray 
        if(start==i-1){
            return 1;
        }

        result = Math.min(result, i-start);
        sum=sum-nums[start];
        start++;

    }else{
        if(i==nums.length)
            break;
        sum = sum+nums[i];
        i++;    
    }
}

if(exists)
    return result;
else
    return 0;
}

Here's the most straight forward way to go about the problem--though this is not going to be the most efficient algorithm to solve the problem.这是解决问题的最直接方法——尽管这不会是解决问题的最有效算法。

You need the fewest number of elements in an array that sum up to something greater than some given number.您需要数组中最少数量的元素总和大于某个给定数字。 Let's call the number of elements needed to do so s .让我们称这样做所需的元素数量为s Then the smallest value of s would occur when we take the largest few elements needed to surpass your minimum number.然后,当我们采用超过您的最小数量所需的最大几个元素时,就会出现s的最小值。

Therefore the most direct solution would be to sort the array from greatest to least, and then loop through the elements until you surpass your minimum number.因此,最直接的解决方案是将数组从最大到最小排序,然后循环遍历元素,直到超过最小数量。 Then you would determine s from the index you stopped at.然后,您将从停止的索引中确定s

The runtime complexity for this algorithm is O(nlogn) for the sorting portion, and then O(n) for the second portion.该算法的运行时复杂度是排序部分的 O(nlogn),然后是第二部分的 O(n)。 Thus the algorithm is O(nlogn) + o(n) = O(nlogn) run time complexity.因此该算法是 O(nlogn) + o(n) = O(nlogn) 运行时间复杂度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM