题目:
- 有序数组的平方,209.长度最小的子数组,59.螺旋矩阵II
学习内容:
977.有序数组的平方
出现数组平方后顺序变化的原因存在负数,那么数组平方的最大值就在数组的两端,不可能在中间。 这是能适用双指针法的原因。
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0;
int right = nums.length - 1;
int i = nums.length - 1;
int[] res = new int[nums.length];
while (left <= right) {
if ((nums[left]*nums[left]) < (nums[right]*nums[right])) {
res[i] = nums[right] * nums[right];
i--;
right--;
} else {
res[i] = nums[left] * nums[left];
i--;
left++;
}
}
return res;
}
}
时间复杂度:O(n)
空间复杂度:O(1)
209. 长度最小的子数组
-
暴力法
时间复杂度:O( n 2 n^2 n2)
空间复杂度:O(1) -
双指针法(滑动窗口)
只用一个for循环,那么这个循环的索引,一定是表示 滑动窗口的终止位置。终止位置规律移动,不断调整开始指针。
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int left = 0;
int sum = 0;
int length = Integer.MAX_VALUE; // 初始化为int的最大值
// 右指针遍历
for (int right = 0; right < nums.length; right++) {
sum += nums[right];
// 当区间和大于等于target时,开始移动左指针
while (sum >= target) {
length = Math.min(length, right - left + 1);
sum -= nums[left]; // 减去最左的值
left++; // 移动左指针
}
}
return length == Integer.MAX_VALUE ? 0 : length;
}
}
时间复杂度:O(n)
空间复杂度:O(1)
59.螺旋矩阵
核心:循环不变量(坚持一个规则到底,处理每一条边)
如:左闭右开,即处理一条边,处理第一个节点,但不处理最后一个节点。
class Solution {
public int[][] generateMatrix(int n) {
int loop = 0; // 控制循环次数
int[][] res = new int[n][n];
int start = 0; // 每次循环的开始点(start, start)
int count = 1; // 定义填充数字
int i, j;
while (loop++ < n / 2) { // 判断边界后,loop从1开始
// 模拟上侧从左到右
for (j = start; j < n - loop; j++) {
res[start][j] = count++;
}
// 模拟右侧从上到下
for (i = start; i < n - loop; i++) {
res[i][j] = count++;
}
// 模拟下侧从右到左
for (; j >= loop; j--) {
res[i][j] = count++;
}
// 模拟左侧从下到上
for (; i >= loop; i--) {
res[i][j] = count++;
}
start++;
}
if (n % 2 == 1) {
res[start][start] = count;
}
return res;
}
}
学习时间:
2024.3.7