代码随想录算法训练营day02|209.长度最小的子数组,59.螺旋矩阵II

209.长度最小的子数组

题目链接:https://leetcode.cn/problems/minimum-size-subarray-sum/description/

我的代码(暴力解法):

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int result = INT_MAX;
        bool flag = false;
        for (int i = 0; i < nums.size(); i++) {
            int count = 0, sum = 0;
            for (int j = i; j < nums.size(); j++) {
                sum += nums[j];
                count++;
                if (sum >= target) {
                    if (result > count)
                        result = count;
                    flag = true;
                    break;
                }
            }
        }
        if (flag == false)
            return 0;
        else
            return result;
    }
};

暴力遍历会超时,通过18/21个用例。

滑动窗口:

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int i = 0, sum = 0;
        int result = INT_MAX;
        bool flag = false;
        for (int j = 0; j < nums.size(); j++) {
            sum += nums[j];
            while (sum >= target) {
                result = min(result, j - i + 1);
                sum -= nums[i];
                i++;
                flag = true;
            }
        }
        return flag == true ? result : 0;
    }
};

j指向的是子数组的终止端,从前向后移动。当检测到子数组元素和大于等于索引值,从前向后移动起始端指针i,不断更新子数组最小长度。

59.螺旋矩阵II

题目链接:https://leetcode.cn/problems/spiral-matrix-ii/description/

我的代码:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> nums(n, vector<int>(n, 0));
        int i = 0, j = 0, start = 0, count = 1, offset = 1;
        while (start < n / 2) { // 绕圈的次数是n/2次
            for (j = start; j < n - offset; j++) {
                nums[start][j] = count++;
            }
            for (i = start; i < n - offset; i++) {
                nums[i][j] = count++;
            }
            for (; j > start; j--) {
                nums[i][j] = count++;
            }
            for (; i > start; i--) {
                nums[i][j] = count++;
            }
            start++;
            offset++;
        }
        if (n % 2 == 1)
            nums[n / 2][n / 2] = count; // n为奇数时中心点单独处理
        return nums;
    }
};

本题不涉及复杂算法,注意模拟过程中循环不变量原则,例如对边的处理左闭右开。

posted @ 2024-08-02 03:19  kurumaruq  阅读(32)  评论(0)    收藏  举报