977.有序数组的平方
209.长度最小的子数组
59.螺旋矩阵II
双指针,滑动窗口,模拟
977.有序数组的平方
双指针
class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length;
int l = 0, r = n-1, idx = n-1;
int[] res = new int[n];
while (l <= r) {
if (nums[l]*nums[l] < nums[r]*nums[r]) {
res[idx--] = nums[r]*nums[r];
r--;
} else {
res[idx--] = nums[l]*nums[l];
l++;
}
}
return res;
}
}
209.长度最小的子数组
滑动窗口:
遍历右边界,不断更新左边界。
// 更新滑动窗口左边界
while (sum >= target) {
res = Math.min(res, j - i + 1);
sum -= nums[i];
}
解法:
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int wnd_sum = 0;
int i = 0;
int res_len = Integer.MAX_VALUE;
for (int j = 0; j < nums.length; j++) {
wnd_sum += nums[j];
while (wnd_sum >= target) {
int len = j - i + 1;
res_len = Math.min(len, res_len);
wnd_sum -= nums[i++];
}
}
return res_len == Integer.MAX_VALUE ? 0 : res_len;
}
}
59.螺旋矩阵II
模拟,注意数组边界的处理,左闭右开还是左开右闭?
本题选择左闭右闭写法代码短一些,因为行列为奇数时,需要单独处理最中间的数值。
class Solution {
public int[][] generateMatrix(int n) {
int[][] matris = new int[n][n];
int top = 0, bottom = n-1, left = 0, right = n-1;
int count = 1;
while (top <= bottom && left <= right) {
// 上
for (int i=left; i <= right; i++) {
matris[top][i] = count++;
}
// 右
for (int i=top+1; i <= bottom; i++) {
matris[i][right] = count++;
}
// 下
for (int i=right-1; i>=left; i--) {
matris[bottom][i] = count++;
}
// 左
for (int i=bottom-1; i>top; i--) {
matris[i][left] = count++;
}
top++;
bottom--;
left++;
right--;
}
return matris;
}
}
左闭右开:
class Solution {
public int[][] generateMatrix(int n) {
int[][] matris = new int[n][n];
int top = 0, bottom = n-1, left = 0, right = n-1;
int count = 1;
while (top <= bottom && left <= right) {
// 上
for (int i=left; i < right; i++) {
matris[top][i] = count++;
}
// 右
for (int i=top; i < bottom; i++) {
matris[i][right] = count++;
}
// 下
for (int i=right; i>left; i--) {
matris[bottom][i] = count++;
}
// 左
for (int i=bottom; i>top; i--) {
matris[i][left] = count++;
}
top++;
bottom--;
left++;
right--;
}
if (n % 2 != 0) {
matris[n/2][n/2] = count;
}
return matris;
}
}
总结
滑动窗口,遍历右边界,循环更新左边界。
模拟,注意边界处理。