题目来源:leetcode
题目描述:
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).
我的解法:第一个想到的就是递归和分治,每次头坐标向后移一位找到当前的最短子序列,然后与之前的对比,取不为0的最小值。但此方法繁琐,不推荐使用
1 class Solution { 2 public int minSubArrayLen(int s, int[] nums) { 3 return sub(0,s,nums);//开始寻找 4 } 5 public int sub(int i,int s,int[] nums)//i为当前其实坐标,s和值,nums数组 6 { 7 if(i>=nums.length) return 0;//当达到数组尾端返回0 8 int count=0,sum=0; 9 for(int j=i;j<nums.length;++j)//遍历当前数组找到大于等于和值的位数 10 { 11 if(sum<s) {sum+=nums[j]; ++count;} 12 else break; 13 } 14 if(sum<s) count=0;//如果找不到返回0 15 int countnext=sub(i+1,s,nums);//移位后的数组函数 16 if(countnext==0) return count; 17 if(count<countnext) return count; 18 else return countnext; 19 20 } 21 }
其他解法:遍历数组的同时,前端和尾端是同时移动的,当达到和值时,先保存位数,前端向后移一位,移到不满足条件时,后端开始移动。同样每次移动之后保存的都是满足条件的最小值
1 class Solution { 2 public int minSubArrayLen(int s, int[] nums) { 3 if (nums == null || nums.length == 0) { 4 return 0; 5 } 6 int N = nums.length; 7 int min = Integer.MAX_VALUE; 8 int left = 0; 9 int sum = 0; 10 11 for(int i = 0; i < N; i++) { 12 sum += nums[i]; 13 while(sum >= s) { 14 min = Math.min(min, i - left + 1); 15 if(min == 1) { 16 return min; 17 } 18 sum -= nums[left++];//前端向后移动 19 } 20 } 21 22 return min != Integer.MAX_VALUE ? min : 0; 23 } 24 }