209.长度最小的子数组
题目链接:. - 力扣(LeetCode)
滑动窗口解法,滑动窗口有点像能吃能拉的贪吃蛇,j指针是头,i指针是尾。核心思想在于构造一个由左右指针组成的窗口,并根据问题的需求不断调整窗口的大小和位置。
为什么能用滑动窗口:分析的对象是一段连续的区间。
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int i = 0;
int sum = 0;
int minlen = nums.length+1;
int L = 0;
for(int j = 0; j < nums.length; j++){
sum += nums[j];
while(sum >= target){
L = j - i + 1;
minlen = (L < minlen)? L:minlen;
sum -= nums[i++];
}
}
if(minlen == nums.length){
return 0;
}
return minlen;
}
}
//leetcode submit region end(Prohibit modification and deletion)
59.螺旋矩阵II
题目链接:. - 力扣(LeetCode)
注意循环不变量,每次都不判断边界最后一个元素,留给下一次循环作为开头判断。
用圈数loop来判断循环条件,直接用n判断一直没调通,其实常数级的内存量多用几个没关系。
class Solution {
public int[][] generateMatrix(int n) {
int starty = 0,count = 1, startx = 0,offset = 1;
int i = 0,j = 0;
int loop = 1;
int[][] res = new int[n][n];
while(loop <= n/2){
for(j = starty; j < n - offset; j++){
res[startx][j] = count++;
}
for(i = startx; i < n - offset; i++){
res[i][j] = count++;
}
for(;j > starty; j--){
res[i][j] = count++;
}
for(;i > startx; i--){
res[i][j] = count++;
}
startx++;
starty++;
offset++;
loop++;
}
if(n%2 !=0 ){
res[n/2][n/2] = n*n;
}
return res;
}
}