题解 | #牛群保卫战#
牛群保卫战
https://www.nowcoder.com/practice/c836930db162418f87874ac5ba84726b
题目考察的知识点
考察双指针滑动窗口的应用
题目解答方法的文字分析
使用双指针维持一段窗口,初值都从0开始,快指针每次遍历将指定的值加入curSum中,如果说大于等于target,记录长度并移动左指针,不断迭代记录满足要求的最短长度返回即可。
本题解析所用的编程语言
使用Java解答
完整且正确的编程代码
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param target int整型
* @param nums int整型一维数组
* @return int整型
*/
public int findMinSubarrayLength (int target, int[] nums) {
// write code here
// 滑动窗口解答
int left = 0, right = 0;
int curSum = 0, minlength = 0;
while (right < nums.length) {
curSum += nums[right];
while (curSum >= target) {
if (minlength == 0 || right - left + 1 < minlength) {
minlength = right - left + 1;
}
curSum -= nums[left];
left++;
}
right++;
}
return minlength;
}
}


查看13道真题和解析