https://leetcode-cn.com/problems/minimum-size-subarray-sum/
暴力解法:
class Solution {
/*暴力解法 */
public int minSubArrayLen(int target, int[] nums) {
int sum = 0;
int result = Integer.MAX_VALUE;
int tempResult = 0;
for (int i = 0; i < nums.length; i++) {
sum = 0;
for (int j = i; j < nums.length; j++) {
sum += nums[j];
if (sum >= target) {
tempResult = j - i + 1;
result = result < tempResult ? result :tempResult;
break;
}
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
}
滑动窗口解法:
class Solution {
/*滑动窗口解法 */
public int minSubArrayLen(int target, int[] nums) {
int sum = 0;
int result = Integer.MAX_VALUE;
int left = 0;
for (int right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum >= target) {
result = Integer.min(result, right - left + 1);
sum -= nums[left++];
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
}
差的真的挺夸张的: