首页 > 其他 > 详细

Minimum Size Subarray Sum

时间:2019-12-21 23:12:14      阅读:112      评论:0      收藏:0      [点我收藏+]

Description

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 -1 instead.

Example

Example 1:

Input: [2,3,1,2,4,3], s = 7
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.

Example 2:

Input: [1, 2, 3, 4, 5], s = 100
Output: -1

Challenge

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

思路:

用两根指针对数组进行一次遍历即可.

如果当前和小于s, 右指针右移, 扩大区间, 反之左指针右移, 缩小区间.

在这个过程中维持区间的和不小于s, 然后更新答案即可.

public class Solution {
    /**
     * @param nums: an array of integers
     * @param s: An integer
     * @return: an integer representing the minimum size of subarray
     */
    public int minimumSize(int[] nums, int s) {
        int ans = Integer.MAX_VALUE;
        int i, j = 0;
        int sum = 0;
        //for 循环主指针
        for (i = 0; i < nums.length; i++) {
            sum += nums[i];
            // while 循环辅指针
            while(j < nums.length && sum >= s) {
                ans = Math.min(ans, i - j + 1);
                sum -= nums[j];
                j++;
               
            }
            
        }
        return ans == Integer.MAX_VALUE ? -1 : ans;
        
    }
}

  

Minimum Size Subarray Sum

原文:https://www.cnblogs.com/FLAGyuri/p/12078519.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!