代码随想录算法训练营第二天| 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)。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

「已注销」

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值