My code:
public class Solution {
public int minSubArrayLen(int s, int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int head = 0;
int end = 0;
int sum = 0;
boolean isForward = true;
int minLen = Integer.MAX_VALUE;
while (end < nums.length) {
if (isForward) {
sum += nums[end];
if (sum >= s) {
minLen = Math.min(minLen, end - head + 1);
isForward = false;
}
else {
isForward = true;
end++;
}
}
else {
sum = sum - nums[head];
head++;
if (sum >= s) {
minLen = Math.min(minLen, end - head + 1);
isForward = false;
}
else {
isForward = true;
end++;
}
}
}
return minLen < Integer.MAX_VALUE ? minLen : 0;
}
public static void main(String[] args) {
Solution test = new Solution();
int[] a = {2,3,1,2,4,3};
System.out.println(test.minSubArrayLen(7, a));
}
}
我自己的做法就是 sliding window, O(n)
比較簡單。但是還有一種 O n log n 的做法。
我沒怎么搞懂。
博文放在這里,有機會再研究。
https://leetcode.com/discuss/35378/solutions-java-with-time-complexity-nlogn-with-explanation
**
總結:
sliding window
**
Anyway, Good luck, Richardo!
My code:
public class Solution {
public int minSubArrayLen(int s, int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int min = Integer.MAX_VALUE;
int begin = 0;
int end = 0;
int sum = 0;
while (begin <= end && end < nums.length) {
sum += nums[end];
if (sum >= s) {
min = Math.min(min, end - begin + 1);
sum -= nums[begin];
sum -= nums[end];
begin++;
}
else {
end++;
}
}
if (min == Integer.MAX_VALUE)
return 0;
else
return min;
}
}
這道題木的思路就是 sliding window,但是奇怪的是,為什么時間復雜度是 O(n) 呢?
programcreek 上面對這道題木的解釋很直接簡潔:
We can use 2 points to mark the left and right boundaries of the sliding window. When the sum is greater than the target, shift the left pointer; when the sum is less than the target, shift the right pointer.
參考網址:
http://www.programcreek.com/2014/05/leetcode-minimum-size-subarray-sum-java/
當然,這道題目還有一種 nlogn的解法,
就是以一側為開頭,比如nums[i],新開一個數組一次記錄元素的和。
然后每次用binary search 找最接近target + sum[i]的index,然后求出長度。具體看之前的網頁鏈接。
Anyway, Good luck, Richardo!