leetcode 209. Minimum Size Subarray Sum
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
Example:
Input:s = 7, nums = [2,3,1,2,4,3]Output: 2 Explanation: the subarray[4,3]has the minimal length under the problem constraint.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
中文版:
给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组。如果不存在符合条件的连续子数组,返回 0。
示例:
输入:s = 7, nums = [2,3,1,2,4,3]输出: 2 解释: 子数组[4,3]是该条件下的长度最小的连续子数组。
进阶:
如果你已经完成了O(n) 时间复杂度的解法, 请尝试 O(n log n) 时间复杂度的解法。
解答1:
思路:用双指针
1 class Solution { 2 public int minSubArrayLen(int s, int[] nums) { 3 int sum=0; 4 int l=0; 5 int min=Integer.MAX_VALUE; 6 boolean flag=false; 7 for (int i = 0; i < nums.length; i++) { 8 sum+=nums[i]; 9 while (sum>=s){ 10 flag=true; 11 min=Math.min(i-l+1,min); 12 sum-=nums[l++]; 13 } 14 15 } 16 return flag?min:0; 17 } 18 }
运行结果:

浙公网安备 33010602011771号