mgaw

导航

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

目录

977 有序数组的平方

209 长度最小的子数组

59 螺旋矩阵 II



977 有序数组的平方

新设立数组res,使res的长度与nums相同,已知数组nums按照非递减的方式排序,可以通过双指针法左指针l设置为0,右指针r设置为nums.length - 1,在循环中将绝对值更大的值的数的平方加入到res的末尾并逐渐向左填充res(依照题意res也得按非递减的方式排序),当l > r时退出循环,返回res。 

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

时间复杂度O(n),空间复杂度O(n)。 

209 长度最小的子数组

 我们可以通过滑动窗口的方式解题。

定义res为Integer.MAX_VALUE,sum为0,两个变量l与r初值均设为0,用r在循环中遍历nums,并将nums[r]加到sum中,在第二层循环中判断sum是否大于等于目标值target,如果true,则res取res与r - l + 1中最小值,sum减去sums[l]的值,再次判断sum是否大于等于目标值target,如果不成立,则退出循环,r继续向后遍历。遍历结束后判断res是否为最初值Integer.MAX_VALUE,如果是则返回0,不是则返回res。

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int res = Integer.MAX_VALUE,l = 0,r = l,sum = 0;
        while(r < nums.length){
            sum += nums[r];
            while(sum >= target){
                res = Math.min(r - l + 1,res);
                sum -= nums[l++];
            }
            r++;
        }
        return res == Integer.MAX_VALUE?0:res; 
    }
}

时间复杂度O(n),空间复杂度O(1)。 

59 螺旋矩阵 II

模拟。依照题意进行向右向下向左向上然后再次循环的操作,设置cnt初始值为1,每次移动cnt都进行++操作,当cnt等于n*n时填充完毕,退出循环。

class Solution {
    public int[][] generateMatrix(int n) {
        int l = 0,r = n - 1,w = 0,s = n - 1,cnt = 1;
        int[][] res = new int[n][n];
        while(cnt <= n * n){
            for(int i = l;i <= r;i++)res[w][i] = cnt++;
            w++;
            for(int i = w;i <= s;i++)res[i][r] = cnt++;
            r--;
            for(int i = r;i >= l;i--)res[s][i] = cnt++;
            s--;
            for(int i = s;i >= w;i--)res[i][l] = cnt++;
            l++;
        }
        return res;
    }
}

 时间复杂度O(n^2),空间复杂度O(n^2)。

posted on 2023-10-26 22:34  A魔法恐龙  阅读(13)  评论(0)    收藏  举报  来源