leetcode:Minimum Size Subarray Sum

来源:互联网 发布:网络模式切换 编辑:程序博客网 时间:2024/05/17 08:24

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.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

找出连续长度最短的的子数组大于等于s的值,如果没有返回0
本题目使用分治算法进行求解,
total[i]表示0 - i的子数组和
那么以i为结尾,如果total[i] > s
假设使得以i为结尾的长度且满足子数组大于等于s的开始节点为j,
那么j的取值为 0 <= j <= i -1,
每次二分的去查找临街值j,使得total[i] - total[j] >= s 即可

public class Solution {    public int minSubArrayLen(int s, int[] nums) {        if(nums == null ||nums.length == 0){            return 0;        }        int total[] = new int[nums.length + 1];        int miniLength = nums.length;        for(int i = 1; i < total.length; ++i){            if(nums[i - 1] >= s){                return 1;            }            total[i] = total[i - 1] + nums[i - 1];            if(total[i] == s){                miniLength = Math.min(miniLength, i - 0);            }            else if(total[i] > s){                int left = 0;                int right = i - 1;                while(left < right){                    int mid = (left + right) / 2;                    int diff = total[i] - total[mid];                    if(diff == s){                        miniLength = Math.min(miniLength, i - mid);                        break;                    }                    else if(diff < s){                        right = mid - 1;                    }                    else{                        left = mid + 1;                    }                }                miniLength = Math.min(miniLength, i - left + 1);            }        }        return miniLength == nums.length ? 0 : miniLength;    }}

上面的是log(n!)的时间复杂度,后来想了一下,还有n(N)的时间复杂度的做法

public class Solution {    public int minSubArrayLen(int s, int[] nums) {        int count = 0;        int minCount = 0;        int index = 0;        int startIndex = 0;        int sum = 0;        while (index<nums.length){            sum = sum + nums[index]; //keep adding until sum >= s            index++;            count++;            if (sum>=s){                if (count<minCount || minCount == 0){                    minCount = count;                }                while (sum>s){//keep removing until sum<=s                    sum = sum - nums[startIndex];                    startIndex++;                    count--;                    if (sum>=s && count<minCount){ //if sum is still greater reduce count                        minCount=count;                    }                }            }        }        return minCount;    }}
0 0
原创粉丝点击