209.长度最小的子数组
给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。
示例:
- 输入:s = 7, nums = [2,3,1,2,4,3]
- 输出:2
- 解释:子数组 [4,3] 是该条件下的长度最小的子数组。
提示:
- 1 <= target <= 10^9
- 1 <= nums.length <= 10^5
- 1 <= nums[i] <= 10^5
思路
1. 滑动窗口,超左滑,不够右滑
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int res = Integer.MAX_VALUE;
int l = 0, r = 0;
int prefix = 0;
while(r < nums.length) {
prefix += nums[r];
while(prefix >= target && l <= r) {
res = Math.min(r - l + 1, res);
prefix -= nums[l ++];
}
r ++;
}
return res == Integer.MAX_VALUE ? 0 : res;
}
}
59.螺旋矩阵II
给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
思路
1. 统一按照左闭右开的模式开展。
class Solution {
public int[][] generateMatrix(int n) {
//init
int loop = 1; // 圈数
int x = 0, y = 0; //每圈的起始坐标,左上角为(0,0)
int count = 1;
int offset = 1;
int[][] matrix = new int[n][n];
int i, j;
while (loop <= n / 2) { //圈数为上界/2
// 顶层,均按照左闭右开
for(j = y; j < n - offset; j ++) {
matrix[x][j] = count ++;
}
//右侧
for(i = x; i < n - offset; i ++) {
matrix[i][j] = count ++;
}
//底部
for(;j > y; j --) {
matrix[i][j] = count ++;
}
//左侧
for(;i > x; i --) {
matrix[i][j] = count ++;
}
offset ++;
loop ++;
x ++;
y ++;
}
if(n % 2 == 1) {
matrix[n / 2][n / 2] = n * n;
}
return matrix;
}
}