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

Leetcode 977.有序数组的平方

题目链接

977.有序数组的平方

题解

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int left = 0, right = nums.size() - 1, index = nums.size() - 1;
        vector<int> res(nums.size());
        //vector<int> res;
        while (left <= right) {
            int temp1 = nums[left] * nums[left];
            int temp2 = nums[right] * nums[right];
            if (temp1 < temp2) {
                //res.push_back(temp2);
                res[index --] = temp2;
                right --;
            }
            else {
                //res.push_back(temp1);
                res[index --] = temp1;
                left ++;
            }
        }
        //reverse(res.begin(), res.end());
        return res;
    }
}

Leetcode 209.长度最小的子数组

题目链接

209. 长度最小的子数组

题解

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int start = 0, end = 0, sum =0, sub_length = nums.size() + 1;
        while (end < nums.size()) {
            //while (sum < target && end <nums.size()) {
            sum += nums[end];
            end++;
            //}
            while (sum >= target) {
                sum -= nums[start];
                start++;
                if (end - start +1 < sub_length) {
                sub_length = end - start +1;
                }   
            }
        }    
        if (sub_length == nums.size() + 1) return 0;
        else return sub_length;
    }
};

Leetcode 59.螺旋矩阵II

题目链接

59. 螺旋矩阵 II

题解

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n, 0));
        int left = 0, right = n - 1, up = 0, down = n - 1, index = 1;
        while (1) {
            for (int i = left; i <= right; i ++) res[up][i] = index ++;
            up ++;
            if (up > down) return res;

            for (int i = up; i <= down; i ++) res[i][right] = index ++;
            right --;
            if (left > right) return res;

            for (int i = right; i >= left; i --) res[down][i] = index ++;
            down --;
            if (up > down) return res;
            for (int i = down; i >= up; i --) res[i][left] = index ++;
            left ++;
            if (left > right) return res;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值