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.
More practice:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
解法1:dynamic window O(N)
动态窗口的一种应用。用左右两个指针维护一个窗口,先移动右指针直到加和>=sum, 然后在开始移动左指针,每次移动判断加和是否还满足并且更新最小的差距。
C++
Java
解法2: binary search
用binary search的条件是数组一定是一定程度上有序的。这里把数组变成了一个累加的数组。然后对于每一个加和
sum, 寻找在之后的第一个数字k使得k>=sum+s,找到之后更新坐标。
Java