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: 2Explanation: 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).
题意
给定一个正整数s和一个正整数数组nums,要求在nums中找到一个最短的连续子序列,使其和大于等于s。
思路
滑动窗口法(Two Pointers):连续子数组问题很容易想到使用滑动窗口来解题。用left和right分别指向窗口的左端点和右端点,如果当前窗口内的整数和小于s,则将右端点右移来拉长窗口;如果当前窗口内的整数和大于等于s,判断其长度是否比当前结果小,是则记录,并将左端点右移来缩短窗口。重复以上步骤就能得到一个长度最短且整数和大于等于s的窗口。最坏情况下左右端点都走了一遍数组,所以时间复杂度为%3DO(N)#card=math&code=O%282N%29%3DO%28N%29&height=20&width=112)。
二分查找:新建sum数组,,则问题转化为在数组sum中求一个连续子数组,使其末首之差大于等于s。从左向右遍历,每次固定左端点i,在右半边子数组中利用二分法找到值大于等于
的元素sum[j],判断长度并记录。时间复杂度为
%0A#card=math&code=O%28NlogN%29%0A&height=20&width=77)。
代码实现 - 滑动窗口1
class Solution {public int minSubArrayLen(int s, int[] nums) {if (nums.length == 0) {return 0;}int ans = 0;int left = 0, right = 0;int sum = nums[0];while (right < nums.length) {if (sum < s && right < nums.length - 1) {sum += nums[++right];} else if (sum >= s) {ans = ans == 0 ? right - left + 1 : Math.min(ans, right - left + 1);sum -= nums[left++];} else {break; // 当右端点已经在数组的末尾且sum仍比s小时,可以直接跳出}}return ans;}}
代码实现 - 滑动窗口2
class Solution {public int minSubArrayLen(int s, int[] nums) {int ans = Integer.MAX_VALUE;int sum = 0;int left = 0;for (int right = 0; right < nums.length; right++) {sum += nums[right];while (sum >= s) {ans = Math.min(ans, right - left + 1);sum -= nums[left++];}}return ans == Integer.MAX_VALUE ? 0 : ans;}}
代码实现 - 二分查找
class Solution {public int minSubArrayLen(int s, int[] nums) {if (nums.length == 0) {return 0;}int ans = Integer.MAX_VALUE;int[] sum = new int[nums.length];for (int i = 0; i < nums.length; i++) {sum[i] = i == 0 ? nums[i] : sum[i - 1] + nums[i];// 先处理掉特殊情况if (sum[i] >= s) {ans = Math.min(ans, i + 1);}}// 二分查找符合条件的点for (int i = 0; i < nums.length; i++) {int target = s + sum[i];int left = i + 1, right = nums.length - 1;while (left < right) {int mid = (right - left) / 2 + left;if (sum[mid] < target) {left = mid + 1;} else {ans = Math.min(ans, mid - i);right = mid;}}if (sum[right] >= target) {ans = Math.min(ans, right - i);}}return ans == Integer.MAX_VALUE ? 0 : ans;}}
