LeetCode: square of ordered array

topic

Given an array of integers nums sorted in non-decreasing order, return a new array consisting of the square of each number, also sorted in non-decreasing order.
Example 1:

Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100]
After sorting, the array becomes is [0,1,9,16,100]

Example 2:

Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]

hint:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums is sorted in non-decreasing order

analyze

We need to capture a key piece of information for this question, that is, the original array is non-decreasing. In this case, the maximum value after the square of the array must be the first or last element of the array. After finding it, we can put the largest element into the largest position in the new array, and so on.
At this time we can consider using the double pointer method .
Define a pointer to point to the first element of the array, and then define a pointer to point to the last element of the array. If the square of the head element is greater than the square of the tail element, the maximum value is placed at the position of the maximum value of the new array, and the head pointer moves forward one space; otherwise, the tail pointer moves back one space.
Code (C language):

int* sortedSquares(int* nums, int numsSize, int* returnSize){
    
    
    *returnSize=numsSize;  //新数组大小等于原数组大小
    int left=0,right=numsSize-1; //创建两个指针,right指向数组最后一位元素,left指向数组第一位元素
    int* ret=malloc(sizeof(int)*numsSize); //为新数组分配空间
    int i=numsSize-1;
    for(i=numsSize-1;i>=0;i--){
    
    
        if(nums[left]*nums[left]<nums[right]*nums[right]){
    
    
        	//若右指针指向元素平方比左指针指向元素平方大,将右指针指向元素平方放入结果数组。右指针左移一位
            ret[i]=nums[right]*nums[right];
            right--;
        }else{
    
    
        	//若左指针指向元素平方比右指针指向元素平方大,将左指针指向元素平方放入结果数组。左指针右移一位
            ret[i]=nums[left]*nums[left];
            left++;
        }
    }
    return ret;
}

Guess you like

Origin blog.csdn.net/David_house/article/details/132778728