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

 题目链接:977. 有序数组的平方 - 力扣(LeetCode)

class Solution {
    public int[] sortedSquares(int[] nums) {
        int[] arr = new int[nums.length];
        int left = 0;
        int right = nums.length - 1;
        int i = nums.length - 1;
        while(left <= right){
            if(nums[left] * nums[left] < nums[right] * nums[right]){
                arr[i] = nums[right] * nums[right];
                i--;
                right--;
            }else{
                arr[i] = nums[left] * nums[left];
                i--;
                left++;
            }

        }
        return arr;
    }
}

暴力解法:每个数平方之后用快排

进阶解法:双指针,因为给出的数组是非递减顺序,所以平方后最大的数一定在两头,两个指针一头一尾,慢慢向中间逼近。

题目链接:209. 长度最小的子数组 - 力扣(LeetCode)

lass Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int i = 0;
        int result = nums.length;
        int sum = 0;
        for (int j = 0; j < nums.length; j++){
            sum += nums[j];
            while(sum >= target){
                result = Math.min(result, (j - i + 1));
                sum -= nums[i++];
            }
        }
        if (i == 0 && sum < target){
            return 0;
        }
        return result;
    }
}

双指针,后面的指针先往后走,达到要求之后前面的指针再往后缩进。

题目链接:59. 螺旋矩阵 II - 力扣(LeetCode)

class Solution {
    public int[][] generateMatrix(int n) {
        int loop = 1;
        int startx = 0;
        int starty = 0;
        int i, j;
        int number = 1;
        int[][] result = new int[n][n];
        while(loop <= n/2){
            for(j = starty; j < (n - loop); j ++){
                result[startx][j] = number ++;
            }
            for(i = startx; i < (n - loop); i ++){
                result[i][j] = number ++;
            }
            for( ; j > starty; j --){
                result[i][j] = number ++;
            }
            for( ; i > startx; i --){
                result[i][j] = number ++;
            }
            loop ++;
            startx ++;
            starty ++;
        }
        if (n % 2 == 1){
            result[startx][starty] = number;
        }
        return result;
    }
}

​​​​​​​​​​​

主要注意以什么来循环,区间,左开右闭,以及n为基数还是偶数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值