代码随想录第2天|LeetCode 977有序数组的平方||209 长度最小的子数组||59 螺旋矩阵 II

LeetCode 977 有序数组的平方

题目链接: 977 有序数组的平方

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* sortedSquares(int* nums, int numsSize, int* returnSize) {
    *returnSize = numsSize;
      int *renum=(int*)malloc(numsSize*sizeof(int));
      int k;
      int i=0;
      int j=numsSize-1;
     for(k=numsSize-1;k>=0;k--){
         int left=nums[i]*nums[i];
         int right=nums[j]*nums[j];
         if(right<left){
             renum[k]=left;
             i++;
             }else{
                 renum[k]=right;
                 j--;

             }
         }
    
    
      return renum;
     }


        
      
  

LeetCode 209 长度最小的子数组

题目链接:209 长度最小的子数组


    int minSubArrayLen(int target, int* nums, int numsSize) {
 int left=0;
 int right;
 int sum=0;
 int minlen=INT_MAX;

 for(right=0;right<numsSize;++right){
    sum+=nums[right];
    while(sum>=target){
        int sublen=right-left+1;
         minlen=minlen<sublen ? minlen:sublen;
        sum-=nums[left++];
    }
}
return minlen==INT_MAX?0:minlen;
}

LeetCode 59 螺旋矩阵 II

题目链接:59. 螺旋矩阵 II

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** generateMatrix(int n, int* returnSize, int** returnColumnSizes){
    //初始化返回的结果数组的大小
    *returnSize = n;
    *returnColumnSizes = (int*)malloc(sizeof(int) * n);
    //初始化返回结果数组ans
    int** ans = (int**)malloc(sizeof(int*) * n);
    int i;
    for(i = 0; i < n; i++) {
        ans[i] = (int*)malloc(sizeof(int) * n);
        (*returnColumnSizes)[i] = n;
    }

    //设置每次循环的起始位置
    int startX = 0;
    int startY = 0;
    //设置二维数组的中间值,若n为奇数。需要最后在中间填入数字
    int mid = n / 2;
    //循环圈数
    int loop = n / 2;
    //偏移数
    int offset = 1;
    //当前要添加的元素
    int count = 1;

    while(loop) {
        int i = startX;
        int j = startY;
        //模拟上侧从左到右
        for(; j < startY + n - offset; j++) {
            ans[startX][j] = count++;
        }
        //模拟右侧从上到下
        for(; i < startX + n - offset; i++) {
            ans[i][j] = count++;
        }
        //模拟下侧从右到左
        for(; j > startY; j--) {
            ans[i][j] = count++;
        }
        //模拟左侧从下到上
        for(; i > startX; i--) {
            ans[i][j] = count++;
        }
        //偏移值每次加2
        offset+=2;
        //遍历起始位置每次+1
        startX++;
        startY++;
        loop--;
    }
    //若n为奇数需要单独给矩阵中间赋值
    if(n%2)
        ans[mid][mid] = count;

    return ans;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值