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

977\有序数组的平方

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int len = nums.size();
        int  k = len-1;
        vector<int> res(len, 0);
        for(int l = 0, r= len-1; l <= r;){	//将步骤加一的操作后置
            if((nums[l] * nums[l]) >= (nums[r] * nums[r])){
                res[k--] = nums[l] * nums[l];
                l++;
            }else{
                res[k--] = nums[r] * nums[r];
                r--;
            }
        }
        return res;
    }
};

209.长度最小的子数组

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int sum = 0;
         int sta = 0;   //起始点
         int res = INT32_MAX;//自定义的最大值  #<limits.h>
         int subLen = 0;
         for(int i = 0; i< nums.size(); i++){
             sum += nums[i];							//每次遍历相加
             while(sum >= target){					//符合条件时递减
                 subLen = i - sta +1;		
                 res = res < subLen ? res : subLen;
                 sum -= nums[sta++];
             }
         }
         res = res == INT32_MAX ? 0 : res;		//判断值是否有效

         return res;
    }
};

59.螺旋矩阵II

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int count = 1;  //数字
        int loop = n / 2;   //圈数
        int offset = 1; //每次右边界减1,
        int startx = 0, starty=0;
        int i, j;
        int mid = n /2;
        vector<vector<int>> res(n, vector<int>(n, 0));

        while(loop--){
            i = startx;	//限定左边的起始位置
            j = starty;

            //左闭右开
            //上行,左到右
            for(j = starty; j < n-offset; j++){
                res[startx][j] = count++;
            }

            //右列,上到下
            for(i=startx; i < n-offset; i++){
                res[i][j] = count++;
            }


            //下边  从右到左
            for(; j > starty; j--){
                res[i][j] = count++;

            }

            //左边   上到下
            for(; i > startx; i--){
                res[i][j] = count++;
            }

            offset += 1 ;	//一圈偏移加1

            startx++;
            starty++;

        }
        if(n % 2){				//奇数的中间位置需要做一个补充
            res[mid][mid] = count;
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值