代码随想录算法训练营 day2

LeetCode 978:有序数组的平方

描述:

给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* sortedSquares(int* nums, int numsSize, int* returnSize){
    int *pinums = (int *)malloc(sizeof(int) * numsSize);
    int i = numsSize - 1;
    int k = i;
    int j = 0;

    while(k != -1)
    {
        if ((nums[j]*nums[j]) > (nums[i]*nums[i]))
        {
            pinums[k--] = nums[j]*nums[j];
            j++;
        }
        else
        {
            pinums[k--] = nums[i]*nums[i];
            i--;
        }
    }
    *returnSize = numsSize;
    return pinums;
}

LeetCode 209:长度最小的子数组

描述

给定一个含有 n 个正整数的数组和一个正整数 target 。找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。

int minSubArrayLen(int target, int* nums, int numsSize){
    int start = 0, end = 0;
    int sum = 0;
    long smlength = -1;
    int length;

    for(; end < numsSize; end ++ )
    {
        sum += nums[end];

        while(sum >= target)
        {
            length = end - start + 1;
            smlength = ((smlength != -1) && (smlength < length))? smlength : length;
            sum -= nums[start++];

        }
    }
    return smlength == -1? 0 : smlength;
}

LeetCode59 螺旋矩阵 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;
}

你可能感兴趣的:(代码随想录刷题打卡,算法,leetcode,数据结构)