代码随想录day2 Java版

1.有序数组的平方

因为数组本身有序,因此最大值只出现在两端,想到左右指针 

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

2.长度最小的子数组

使用滑动窗口思想优化,用双指针实现

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int[] sum = new int[nums.length+1];
        for(int i = 1; i <= nums.length; i++) {
            sum[i] = sum[i-1] + nums[i-1];
        }
        int res = 1000000;
        int i = 0;
        for(int j = 1; j <= nums.length; j++) {
            
            while(sum[j]-sum[i] >= target && i <= j) {
                res = res < j-i?res:j-i ;
                i++;
            }
        }
        if (res == 1000000) return 0;
        return res;
    }
}

3.螺旋数组

就是纯模拟,按照题目描述顺时针遍历

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] nums = new int[n][n];
        int offset = 1,count = 1, sx = 0, sy = 0;
        int loop = n / 2;
        while (loop-- > 0){
            int i = sy, j = sx;
            for (; j < n-offset; j++) {
                nums[sx][j] = count++;
            }
            for (; i < n-offset; i++) {
                nums[i][j] = count++;
            }
            for (; j > sx; j--) {
                nums[i][j] = count++;
            }
            for (; i > sy; i--) {
                nums[i][j] = count++;
            }
            offset++;
            sx++;
            sy++;
        }
        if (n % 2 == 1) {
            nums[n/2][n/2] = count;
        }
        return nums;
    }
}

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值