代码随想录算法训练营第二天 | 977. 有序数组的平方、209. 长度最小的子数组、59. 螺旋矩阵 II

225 阅读1分钟

977. 有序数组的平方

读题要仔细,非递减排序即说明平方最大值只能出现在两端,因此只需要从头部和尾部向中间遍历。

双指针法

初始数组

image.png

最大值出现在右端时: image.png

最大值出现在左端时: image.png

class Solution {

public int[] sortedSquares(int[] nums) {
    int len=nums.length-1;
    for(int i=0;i<=len;i++){
        nums[i]=nums[i]*nums[i];
    }//平方后排序
    /*
    Arrays.sort(nums);
    return nums;*/
    //双指针法
    int result[]=new int[nums.length];
    int index=result.length-1;
    int left=0;int right=len;
    while(left<=right){
        if(nums[left]<nums[right]){
            result[index--]=nums[right--];
        }
        else{
            result[index--]=nums[left++];
        }
    }
    return result;
}

}

209. 长度最小的子数组

滑动窗口思想

查找到可行区间 image.png

缩小可行区间(失败) image.png

缩小可行区间(成功)

image.png

每一次查找成功都与当前result比较,取较小者。

class Solution {

public int minSubArrayLen(int target, int[] nums){
    int left=0;
    int sum=0;
    int result=Integer.MAX_VALUE;
    for(int right=0;right<nums.length;right++){
        sum+=nums[right];
        while(sum>=target){
            result=Math.min(result,right-left+1);
            sum-=nums[left++];
        }
    }
    return result==Integer.MAX_VALUE?0:result;
}

}

59. 螺旋矩阵 II

看了教程,自己写还是困难

class Solution {

public int[][] generateMatrix(int n) {
    int maxNum = n * n;
    int curNum = 1;
    int[][] matrix = new int[n][n];
    int row = 0, column = 0;
    int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // 右下左上
    int directionIndex = 0;
    while (curNum <= maxNum) {
        matrix[row][column] = curNum;
        curNum++;
        int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
        if (nextRow < 0 || nextRow >= n || nextColumn < 0 || nextColumn >= n || matrix[nextRow][nextColumn] != 0) {
            directionIndex = (directionIndex + 1) % 4; // 顺时针旋转至下一个方向
        }
        row = row + directions[directionIndex][0];
        column = column + directions[directionIndex][1];
    }
    return matrix;
}

}