代码随想录算法训练营第二天 | 977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II

有序数组的平方

两边的边界是不好处理的情况,从大到小!

// 双指针 从大到小!!
class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int n = nums.size();
        vector<int> res(n);
        if (n == 1) return {nums[0] * nums[0]};
        int i = 0, j = n - 1, idx = n - 1;
        while (i <= j)
        {
            if (nums[i] * nums[i] <= nums[j] * nums[j])
            {
                res[idx--] = nums[j] * nums[j--];
            }
            else
                res[idx--] = nums[i] * nums[i++];
        }
        return res;
    }
};

长度最小的子数组

很典型的滑动窗口

// 滑动窗口
class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int n = nums.size();
        int sum = 0, minn = 1e9;
        int i = 0, j = 0;
        while (j < n && i <= j)
        {
            sum += nums[j];
            while (sum >= target)
            {
                minn = min(minn, j - i + 1);
                sum -= nums[i];
                i ++;
            }
            j ++;
        }
        return minn == 1e9 ? 0 : minn;
    }
};

螺旋矩阵 II

就是蛇形矩阵

class Solution {
public:
    int dx[4] = {0, 1, 0, -1};
    int dy[4] = {1, 0, -1, 0};
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res;
        res.resize(n);
        for (auto &i : res) i.resize(n);
        int x = 0, y = 0, f = 0, num = 2;
        res[0][0] = 1;
        for (int t = 1; t < n * n; t ++)
        {
            int xx = x + dx[f];
            int yy = y + dy[f];
            if (xx >= n || xx < 0 || yy >= n || yy < 0 || res[xx][yy])
            {
                f = (f + 1) % 4;
                xx = x + dx[f];
                yy = y + dy[f];
            }
            // cout << xx << ' ' << yy << endl;
            res[xx][yy] = num ++;
            x = xx, y = yy;
        }
        return res;
    }
};
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇