首页 > 其他分享 >代码随想录训练营第二天 |977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II

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

时间:2022-10-13 15:00:39浏览次数:72  
标签:977 count int res 随想录 ++ 数组 col row

今天是训练营第二天,包含了第一天双指针的扩展题

977. 有序数组的平方

class Solution {
    public int[] sortedSquares(int[] nums) {
        int n = nums.length;
        int[] res = new int[n];
        int l = 0;
        int r = n-1;
        int i = r;
        while(l <= r){
            if(nums[l]*nums[l] < nums[r]*nums[r]){
                res[i--] = nums[r]*nums[r];
                r--;
            }
            else{
                 res[i--] = nums[l]*nums[l];
                 l++;
            }
        }
        return res;
    }
}

这道题要注意的点就是负数的平方为正数,因此我们从最大的值开始处理就可以了。

209. 长度最小的子数组

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int n = nums.length;
        int res = Integer.MAX_VALUE;
        int l = 0;
        int sum = 0;

        for(int i = 0; i<n; i++){
            sum += nums[i];
            while(sum >= target){
                res = Math.min(res, i - l + 1);
                sum -= nums[l];
                l ++;
            }
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }
}

 

滑动窗口基本题,不断向左扩大窗口,如果窗口中的值超过了target,再缩小窗口右边直至窗口中的值小于等于target,再往复进行。

59. 螺旋矩阵2

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        
        int row = 0;
        int col = 0;
        int count = 1;
        boolean notEnd = true;
        while(notEnd){
            notEnd = false;
            while(col < n && res[row][col]==0){
                res[row][col]= count;
                count ++;
                col ++;
            }
            col--;
            row++;
            while(row < n && res[row][col]==0 ){
                res[row][col]= count;
                count ++;
                row ++;
            }
            col--;
            row--;
            while(col >= 0 && res[row][col]==0){
                res[row][col]= count;
                count ++;
                col --;
            }
            col++;
            row--;

            while(row >= 0 &&res[row][col]==0){
                res[row][col]= count;
                count ++;
                row --;
                notEnd = true;
            }
            row++;
            col++;

        }
        return res;
    }
}

看了题解的方法。 按照四边顺序填充,如果遇到有之前填过的(非0的),就换边

 

今天第二天的训练题目,难度明显比第一天高出不少。

标签:977,count,int,res,随想录,++,数组,col,row
From: https://www.cnblogs.com/catSoda/p/16786724.html

相关文章