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

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

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的),就换边

 

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

posted @   小猫Soda  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示