代码随想录算法训练营 第二日 Leetcode 977 有序数组的平方 Leetcode209 长度最小子数组 Leetcode59 螺旋矩阵Ⅱ
数组第二部分
977 有序数组的平方
双指针思想
数组其实是有序的, 只不过负数平方之后可能成为最大数了。
那么数组平方的最大值就在数组的两端,不是最左边就是最右边,不可能是中间。
此时可以考虑双指针法了,i指向起始位置,j指向终止位置。
定义一个新数组result,和A数组一样的大小,让k指向result数组终止位置。
如果A[i] * A[i] < A[j] * A[j] 那么result[k--] = A[j] * A[j]; 。
如果A[i] * A[i] >= A[j] * A[j] 那么result[k--] = A[i] * A[i]; 。
(题目条件按 非递减顺序 排序的整数数组 nums,根据例子看 左边最小负数,右边最大整数,并不是从0开始 ,才能满足上述思想)

class Solution {
public int[] sortedSquares(int[] nums) {
int[] res = new int[nums.length];
int i = 0,j = nums.length-1;
int k = res.length -1;
for(;k>=0;k--){
if(nums[i] * nums[i] >= nums[j] * nums[j]){
res[k] = nums[i] * nums[i];
i++;
}else{
res[k] = nums[j] * nums[j];
j--;
}
}
return res;
}
}
LeetCode 209 长度最小子数组
滑动窗口思想,双指针
外层循环是右区间指针边界,关键在于左区间指针的移动
满足条件时,通过循环进行左区间指针变化
题解题解
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int i = 0, j = 0;
int sum = 0;
int res = Integer.MAX_VALUE;
for (; j <= nums.length - 1; j++) {
sum += nums[j];
while (sum >= target) {
res = res > (j - i + 1) ? (j - i + 1) : res;
sum -= nums[i++];
}
}
return res == Integer.MAX_VALUE ? 0 : res;
}
}
LeetCode 59 螺旋矩阵2
经典题目 模拟题 注意区间边界
思路 一圈一圈模拟,但要注意每一条边模拟的边界问题 都要左闭右开

外层循环----模拟的圈数 n/2 如果n为奇数 最后补上中心
起始位置 分别是 每圈的左上角 startx starty
offset偏移位 自增
内层四个循环 分别是四条方向的边 循环赋值
- 填充上行从左到右
- 填充右列从上到下
- 填充下行从右到左
- 填充左列从下到上
class Solution {
public int[][] generateMatrix(int n) {
int count = 1;
int loops = n / 2;
int startx = 0;
int starty = 0;
int offset = 1;
int[][] res = new int[n][n];
for(;loops>0;loops--){
int i = startx;
int j = starty;
for(;j < n - offset;j++){
res[i][j] = count++;
}
for(;i < n-offset;i++){
res[i][j] = count++;
}
for(;j > offset-1 ;j--){
res[i][j] = count++;
}
for(;i > offset -1 ;i--){
res[i][j] = count++;
}
offset++;
startx++;
starty++;
}
if(n % 2 == 1 ){
res[n/2][n/2] = count;
}
return res;
}
}

浙公网安备 33010602011771号