代码随想录DAY2:有序数组的平方 + 长度最小的子数组 + 螺旋矩阵II

1. 有序数组的平方

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int left = 0;
        int right = nums.size()-1;
        int k = nums.size() - 1;
        vector<int> result(nums.size(),0);
        while (left <= right){
            int left_num = nums[left] * nums[left];
            int right_num = nums[right] * nums[right];
            if (left_num < right_num){
                result[k] = right_num;
                right--;
                
            }
            else {
                result[k] = left_num;
                left++;
            }
            k--;
        }
        return result;
    }
};

2. 长度最小的子数组

【重点】滑动窗口

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int slow = 0;
        int quicksum = 0;
        int len = 0;
        int result = INT32_MAX;
        for (int fast = 0; fast <= nums.size()-1; fast++){
            quicksum += nums[fast];
            while(quicksum >= target) {
                len = fast - slow + 1;
                result = result < len ? result : len;
                quicksum -= nums[slow++];

            }
        }
        return result == INT32_MAX ? 0 : result;
    }
};

3. 螺旋矩阵II

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int startx = 0;
        int starty = 0;
        int loop = n/2;
        int offset = 1;
        int count = 1;
        vector<vector<int>> result(n,vector<int>(n,0));
        while (loop--) {
            int i = startx;
            int j = starty;

            for (j; j < n-offset; j++) {
                result[i][j] = count;
                count++;
            }
            for (i; i < n-offset; i++) {
                result[i][j] = count;
                count++;
            }
            for (j;j > starty; j--) {
                result[i][j] = count;
                count++;
            }
            for (i;i > starty; i--) {
                result[i][j] = count;
                count++;
            }
            startx++;
            starty++;
            offset++;
        }
        if (n%2 != 0){
            result[n/2][n/2] = count;
        }
        return result;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值