Day2力扣打卡

打卡记录

无限数组的最短子数组(滑动窗口)

链接

思路:先求单个数组的总和,再对两个重复数组所组成的新数组上使用 不定长的滑动窗口 来求得满足目标的最小长度。

cpp 复制代码
class Solution {
public:
    int minSizeSubarray(vector<int>& nums, int target) {
        long long sum = accumulate(nums.begin(), nums.end(), 0LL);
        int ans = 0x3f3f3f3f, n = nums.size(), cnt = 0;
        for (int i = 0, j = 0; i < n * 2; ++i)
        {
            cnt += nums[i % n];
            while (cnt > target % sum)
                cnt -= nums[j++ % n];
            if (cnt == target % sum) ans = min(ans, i - j + 1);
        }
        return ans == 0x3f3f3f3f ? -1 : ans + target / sum * n; 
    }
};

螺旋矩阵 II(模拟)

链接

模拟向四个方向依次行进,遇到边缘调转为下个方向,同时遇到已经赋值过的位置也进行调转方向的操作。

cpp 复制代码
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int dx[4]{0, 1, 0, -1}, dy[4]{1, 0, -1, 0}, cnt = 0;
        int x = 0, y = 0, idx = 0;
        vector<vector<int>> mat(n, vector<int> (n, -1));
        while (cnt++ != n * n) {
            mat[x][y] = cnt;
            if (x + dx[idx] < 0 || x + dx[idx] >= n || y + dy[idx] < 0 || y + dy[idx] >= n 
            || mat[x + dx[idx]][y + dy[idx]] != -1)
                idx = (idx + 1) % 4;
            x += dx[idx], y += dy[idx];
        }
        return mat;
    }
};
相关推荐
报错小能手1 天前
C++笔记——STL map
c++·笔记
思麟呀1 天前
Linux的基础IO流
linux·运维·服务器·开发语言·c++
星释1 天前
Rust 练习册 :Pythagorean Triplet与数学算法
开发语言·算法·rust
星释1 天前
Rust 练习册 :Nth Prime与素数算法
开发语言·算法·rust
多喝开水少熬夜1 天前
Trie树相关算法题java实现
java·开发语言·算法
QT 小鲜肉1 天前
【QT/C++】Qt定时器QTimer类的实现方法详解(超详细)
开发语言·数据库·c++·笔记·qt·学习
WBluuue1 天前
数据结构与算法:树上倍增与LCA
数据结构·c++·算法
bruk_spp1 天前
牛客网华为在线编程题
算法
呆瑜nuage1 天前
C++之红黑树
c++
亮剑20181 天前
第2节:程序逻辑与控制流——让程序“思考”
开发语言·c++·人工智能