代码随想录算法训练营第二天 补 | 长度最小的子数组、螺旋矩阵II、区间和、开发商购买土地

长度最小的子数组

采用滑动窗口法,后指针一直运动到满足条件,前指针移动一格(满足条件前动,不满足后动)

/*
 * @lc app=leetcode.cn id=209 lang=java
 *
 * [209] 长度最小的子数组
 */

// @lc code=start

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int left = 0;
        int min = nums.length + 1;
        int temp = 0;
        for (int right = 0; right < nums.length; right++) {
            temp += nums[right];
            while (temp >= target) {
                min = Math.min(min, right - left + 1);
                temp -= nums[left++];
            }
        }
        return min == nums.length + 1 ? 0 : min;
    }
}
// @lc code=end

螺旋矩阵II

主要是要搞定变量的维护和条件的判定,确定区间形式

/*
 * @lc app=leetcode.cn id=59 lang=java
 *
 * [59] 螺旋矩阵 II
 */

// @lc code=start
class Solution {
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        int top = 0;
        int botton = n - 1;
        int left = 0;
        int right = n - 1;
        int i = 1;
        int temp = left;
        while (i <= n * n) {
            temp = left;
            while (left <= right && top <= botton) {
                result[top][left] = i++;
                left++;
            }
            left = temp;
            top++;

            temp = top;
            while (top <= botton && left <= right) {
                result[top][right] = i++;
                top++;
            }
            right--;
            top = temp;
    
            temp = right;
            while (right >= left && top <= botton) {
                result[botton][right] = i++;
                right--;
            }
            right = temp;
            botton--;

            temp = botton;
            while (botton >= top && right >= left) {
                result[botton][left] = i++;
                botton--;
            }
            botton = temp;
            left++;

            System.out.printf("%d %d %d %d\n", left, right, top, botton);
        }
        return result;
    }
}
// @lc code=end

区间和 & 开发商购买土地

采取前缀和的思想,可以节省计算量

posted @ 2026-03-09 00:56  月鸣  阅读(0)  评论(0)    收藏  举报