代码随想录Day2

有序数组的平方

看完题目直接写了一个最简单的解法

class Solution {
    public int[] sortedSquares(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            nums[i] = nums[i] * nums[i];
        }
        Arrays.sort(nums);
        return nums;
    }
}

但是这种解法时间复杂度不符合题目要求,想到了昨天的双指针,写了一个满足条件的双指针版本

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

长度最小的子数组

读完题知道这是滑动窗口,但是太长时间没用过了,依稀记得以前学的时候老师告诉我是固定右端点,然后不断调整左端点。但是写了半天还是没过,最后看了卡哥的题解,发现了错误点,改正记录。

ps:这道题还要注意它存在不符合条件的子数组,最开始没特判这种情况返回值直接错了。。。。

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int size = nums.length;
        int res = Integer.MAX_VALUE; //判断值
        int sum = 0;
        int l = 0;
        for(int r = 0; r < size; r++) {  //移动右端点
            sum += nums[r];
            while(sum >= target) { 
                res = Math.min(res, r - l + 1); 
                sum -= nums[l];  
                l ++;  //左端点向前推进
            }
        }
        return res == Integer.MAX_VALUE? 0: res;  //注意题目条件 特判
    }
}

螺旋矩阵

模拟题,但是边界处理真的很折磨
看了题解之后自己写了一遍,需要注意的点就是循环几次和循环条件的问题,画图可以更好理解

class Solution {
    public int[][] generateMatrix(int n) {
        int loop = 0;
        int start = 0;
        int count = 1;
        int[][] res = new int[n][n];
        int i, j;
        while (loop++ < n / 2) {
            for (j = start; j < n - loop; j++) {
                res[start][j] = count++;
            }

            for (i = start; i < n - loop; i++) {
                res[i][j] = count++;
            }

            for(; j >= loop; j--) {
                res[i][j] = count++;
            }

            for(; i >= loop; i--) {
                res[i][j] = count++;
            }

            start++;
        }

        if(n % 2 == 1) {
            res[start][start] = count;
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值