代码随想录算法训练营第二天| LeetCode977 有序数组的平方、LeetCode209 长度最小的子数组、LeetCode59 螺旋矩阵

LeetCode977 有序数组的平方

题目链接:https://leetcode.cn/problems/squares-of-a-sorted-array/

方法:双指针

    public int[] sortedSquares(int[] nums) {
        int left = 0;
        int right = nums.length - 1;
        int[] result = new int[nums.length];
        int k = result.length - 1;

        while (left <= right) {
            if (nums[left] * nums[left] > nums[right] * nums[right]) {
                result[k--] = nums[left] * nums[left];
                left++;
            } else {
                result[k--] = nums[right] * nums[right];
                right--;
            }
        }
        return result;

思路:从两端向中间靠拢,因为最大值只可能出现在两端,然后从末尾开始填充新数组

LeetCode209 长度最小的子数组

题目链接:https://leetcode.cn/problems/minimum-size-subarray-sum/

方法:滑动窗口

    // 滑动窗口
    public int minSubArrayLen(int target, int[] nums) {
        int slow = 0;
        int sum = 0;
        int result = Integer.MAX_VALUE;
        for (int fast = 0; fast < nums.length; fast++) {
            sum += nums[fast];
            while (sum >= target) {
                result = Math.min(result, fast - slow + 1);
                sum -= nums[slow++];
            }
        }
        return result == Integer.MAX_VALUE ? 0 : result;

思路:快指针从头依次向后移动,直到窗口内的和大于等于目标值,然后收缩慢指针,从而得到最小的窗口长度

LeetCode59 螺旋矩阵

题目链接:https://leetcode.cn/problems/spiral-matrix-ii/

方法:上右下左循环填充,收缩边界
    public int[][] generateMatrix(int n) {
        int result[][] = new int[n][n];
        int loop = 1;
        int count = 1;
        int startX = 0;
        int startY = 0;
        int i, j;
        int offset = 1;

        while (loop <= n / 2) {
            // 顶部
            for (j = startY; j < n - offset; j++) {
                result[startX][j] = count++;
            }
            // 右列
            for (i = startX; i < n -offset; i++) {
                result[i][j] = count++;
            }
            // 底部
            for (; j > startY; j--) {
                result[i][j] = count++;
            }
            // 左列
            for (; i > startX; i--) {
                result[i][j] = count++;
            }
            loop++;
            offset++;
            startX++;
            startY++;
        }
        if (n % 2 == 1) {
            result[startX][startY] = n * n;
        }
        return result;

心得:之前没有做过螺旋矩阵的题目,很有收获,注意边界值的问题就不容易出错了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值