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.
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.
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
https://leetcode.com/problems/minimum-size-subarray-sum/solution/
链接中给出的解答非常全面,暴力搜索会导致超时,用空间换时间会使得时间复杂度降低到n^2,通过使用二叉搜索可以使得复杂度进一步降低,这道题最好的方法是使用双指针,分别表示子序列的头和尾,遍历整个数组,sum表示之前所有元素之和,内部的while循环则每次去除下表最小的元素,逐步找到最短的符合要求子序列,最后结果返回ans
要点:贪心算法
伪代码如下:
1、初始化left = 0, sum = 0
2、for i = 0 to n 循环
sum累加
计算符合要求的子序列的长度,跟新ans
ps:最开始我也怀疑这么做能否找到最优解,后来仔细想了一下,这样做可以遍历所有的恰好满足要求的连续子数组,必定会找到最优解。
1 int minSubArrayLen(int s, vector<int>& nums) 2 { 3 int n = nums.size(); 4 int ans = INT_MAX; 5 int left = 0; 6 int sum = 0; 7 for (int i = 0; i < n; i++) { 8 sum += nums[i]; 9 while (sum >= s) { 10 ans = min(ans, i + 1 - left); 11 sum -= nums[left++]; 12 } 13 } 14 return (ans != INT_MAX) ? ans : 0; 15 }
时间复杂度:O(n),每个元素最多被左右两个指针遍历两次。
空间复杂度:O(1)
二刷,笔写,2018-03-14,看着解释基本AC