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).
<Solution>
想法如下
- 用一個變數計算目前的 sum,當 sum >= s 的時候,開始找答案
- 當 sum >= s 這個條件成立時,計算出目前的 subarray 長度,然後縮起始位置並減掉該位置的值,看看 sum >= s 這個條件是不是還是成立,是的話,再重複做之前的動作
Java(參考解法)
kotlin
沒有留言:
張貼留言