2018年6月21日 星期四

[LeetCode] 209. Minimum Size Subarray Sum

轉自LeetCode

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 這個條件是不是還是成立,是的話,再重複做之前的動作
code 如下

Java(參考解法)
class Solution {
public int minSubArrayLen(int s, int[] nums) {
int sum = 0, left = 0, ans = Integer.MAX_VALUE;
for(int i = 0; i < nums.length; i++) {
sum += nums[i];
while(sum >= s) {
ans = Math.min(ans, i - left + 1);
sum -= nums[left++];
}
}
return ans == Integer.MAX_VALUE ? 0 : ans;
}
}

kotlin
class Solution {
fun minSubArrayLen(target: Int, nums: IntArray): Int {
var ans = Int.MAX_VALUE
var left = 0
var sum = 0
for(right in nums.indices) {
sum += nums[right]
while(sum >= target) {
ans = Math.min(ans, right-left+1)
sum -= nums[left++]
}
}
return if(ans == Int.MAX_VALUE) 0 else ans
}
}

沒有留言:

張貼留言