leetcode leetcode 209 : Minimum Size Subarray Sum | Java最短代码实现

Total Accepted: 33397 Total Submissions: 126933 Difficulty: Medium

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).

【抛砖】

时间复杂度O(n)——定义2指针start和end指针,并更新minLen:

1.end先右移,直到第一次满足sum≥s

2.start开始右移,直到第一次满足sum < s:

    public int minSubArrayLen(int s, int[] nums) {
        int start = 0, sum = 0, minLen = Integer.MAX_VALUE;
        for (int end = 0; end < nums.length; end++) {
            sum += nums[end];
            while (sum >= s) {
                minLen = Math.min(minLen, end - start + 1);
                sum -= nums[start++];
            }
        }
        return minLen;
    }
14 / 14  test cases passed. Runtime: 1 ms  Your runtime beats 18.63% of javasubmissions.
【补充】

时间复杂度O(nlogn)——先求出nums的和函数sum,当sum[i] >= s时,用二分法找到在sum的[0,i]区间中找最右边的小于sum[i] - target的数sum[index]的index,然后求出minLen = i - index,如此不断更新。注意index最小可到-1:

    public int minSubArrayLen(int s, int[] nums) {
        int[] sum = new int[nums.length];
        int minLen = Integer.MAX_VALUE;
        if (nums.length != 0) sum[0] = nums[0];
        for (int i = 1; i < nums.length; i++) sum[i] = sum[i - 1] + nums[i];
        for (int i = 0; i < nums.length; i++)
            if (sum[i] >= s)
                minLen = Math.min(minLen, i - binarySearchLastIndexNotBiggerThanTarget(0, i, sum[i] - s, sum));
        return minLen == Integer.MAX_VALUE ? 0 : minLen;
    }
    int binarySearchLastIndexNotBiggerThanTarget(int left, int right, int target, int[] sum) {
        while (left <= right) {
            int mid = (left + right) >> 1;
            if (sum[mid] > target) right = mid - 1;
            else left = mid + 1;
        }
        return right;
    }

14 / 14 test cases passed. Runtime: 3 ms  Your runtime beats 6.83% of javasubmissions.

欢迎优化!
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值