2. leetcode209.长度最小的子数组 59.螺旋矩阵II

209.长度最小的子数组

力扣题目链接(opens new window)

给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。

示例:

  • 输入:s = 7, nums = [2,3,1,2,4,3]
  • 输出:2
  • 解释:子数组 [4,3] 是该条件下的长度最小的子数组。

提示:

  • 1 <= target <= 10^9
  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^5

思路

1. 滑动窗口,超左滑,不够右滑

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int res = Integer.MAX_VALUE;
        int l = 0, r = 0;
        int prefix = 0;
        while(r < nums.length) {
            prefix += nums[r];
            while(prefix >= target && l <= r) {
                res = Math.min(r - l + 1, res);
                prefix -= nums[l ++];
            } 
            r ++;
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }
}

59.螺旋矩阵II

力扣题目链接(opens new window)

给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]

思路

1. 统一按照左闭右开的模式开展。

class Solution {
    public int[][] generateMatrix(int n) {
        //init
        int loop = 1; // 圈数
        int x = 0, y = 0; //每圈的起始坐标,左上角为(0,0)
        int count = 1;
        int offset = 1;
        int[][] matrix = new int[n][n];
        int i, j;

        while (loop <= n / 2) { //圈数为上界/2
            
            // 顶层,均按照左闭右开
            for(j = y; j < n - offset; j ++) {
                matrix[x][j] = count ++;
            }

            //右侧
            for(i = x; i < n - offset; i ++) {
                matrix[i][j] = count ++;
            }

            //底部
            for(;j > y; j --) {
                matrix[i][j] = count ++;
            }

            //左侧
            for(;i > x; i --) {
                matrix[i][j] = count ++;
            }

            offset ++;
            loop ++;
            x ++;
            y ++;

        }
        if(n % 2 == 1) {
            matrix[n / 2][n / 2] = n * n;
        }
        return matrix;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值