代码随想录算法训练营DAY3第一章 数组part02

目录

[209. 长度最小的子数组](#209. 长度最小的子数组)

[59. 螺旋矩阵 II](#59. 螺旋矩阵 II)

[58. 区间和(第九期模拟笔试)](#58. 区间和(第九期模拟笔试))


209. 长度最小的子数组

cpp 复制代码
class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int sum = 0;
        int len = nums.size() + 1;
        int right = 0;
        for (int left = 0; left < nums.size(); left++) {
            while (sum < target && right < nums.size()) {
                sum += nums[right++];
            }
            if (sum >= target) {
                len = min(right - left, len);
            }
            sum -= nums[left];
        }
        if (len == nums.size() + 1) {
            return 0;
        }
        return len;
    }
};

59. 螺旋矩阵 II

cpp 复制代码
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int num = 1;
        int top = 0;
        int bottom = n - 1;
        int left = 0;
        int right = n - 1;
        vector<vector<int>> ans(n, vector<int>(n));
        while (left <= right && top <= bottom) {
            // 左到右,上界收缩
            for (int i = left; i <= right; i++) {
                ans[top][i] = num++;
            }
            top++;
            // 上到下,右界收缩
            for (int i = top; i <= bottom; i++) {
                ans[i][right] = num++;
            }
            right--;
            // 右到左,下界收缩
            if (top <= bottom) {
                for (int i = right; i >= left; i--) {
                    ans[bottom][i] = num++;
                }
                bottom--;
            }
            // 下到上,左界收缩
            if (left <= right) {
                for (int i = bottom; i >= top; i--) {
                    ans[i][left] = num++;
                }
                left++;
            }
        }
        return ans;
    }
};

58. 区间和(第九期模拟笔试)

cpp 复制代码
#include<iostream>
#include<vector>
using namespace std;
int main(){
    int n;
    cin>>n;
    vector<int> s(n+1);
    for(int i=1;i<=n;i++){
        cin>>s[i];
        s[i]+=s[i-1];
    }
    int a,b;
    while(cin>>a>>b){
        cout<<s[b+1]-s[a]<<endl;
    }
    return 0;
}
相关推荐
Billlly1 天前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives1 天前
atcoder ABC 452 题解
数据结构·算法
feifeigo1231 天前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
java1234_小锋1 天前
Java高频面试题:Springboot的自动配置原理?
java·spring boot·面试
fengfuyao9851 天前
基于STM32的4轴步进电机加减速控制工程源码(梯形加减速算法)
网络·stm32·算法
末央&1 天前
【天机论坛】项目环境搭建和数据库设计
java·数据库
枫叶落雨2221 天前
ShardingSphere 介绍
java
花花鱼1 天前
Spring Security 与 Spring MVC
java·spring·mvc
无敌昊哥战神1 天前
深入理解 C 语言:巧妙利用“0地址”手写 offsetof 宏与内存对齐机制
c语言·数据结构·算法
小白菜又菜1 天前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展