Leetcode刷题计划 第八天 有序数组的平方

Leetcode刷题计划 第八天 有序数组的平方_第1张图片

暴力解题,代码如下:

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

双指针法,代码如下:

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

 

你可能感兴趣的:(leetcode,算法,职场和发展)