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.
题意:
给定含有n个正整数的数组和一个正整数,求最小长度的子数组,使子数组的和sum ≥ s,如果不存在这样的子数组,返回0。
思路:
方法一:
利用滑动窗口机制,用两个指针来维持和的最大值,然后求最小子数组长度。pre和last指针之间维持着大于s的和的子数组,通过减小和扩大滑动窗口大小,来实现查找对小的和大于s的子数组,时间复杂度是O(n)。
1 | class Solution { |
方法二:
时间复杂度是O(nlogn)的算法。
1 | Now let's move on to the O(nlogn) solution. Well, this less efficient solution is far more difficult to come up with. The idea is to first maintain an array of accumulated summations of elements in nums. Specifically, for nums = [2, 3, 1, 2, 4, 3] in the problem statement, sums = [0, 2, 5, 6, 8, 12, 15]. Then for each element in sums, if it is not less than s, we search for the first element that is greater than sums[i] - s (in fact, this is just what the upper_bound function does) in sums using binary search. |
1 | class Solution { |