977. Ordered square array: LeetCode

Given a non-sorted in descending order of an array of integers A, each number Returns a new array consisting of square, requirements are sorted in non-decreasing order.

Example 1 : 

Input: [ - . 4 - 1 , 0 , 3 , 10 ] 
Output: [ 0 , 1 , 9 , 16 , 100 ] 
Example 2 : 

Input: [ - . 7 - 3 , 2 , 3 , 11 ] 
output : [ 4 , 9 , 9 , 49 , 121 ] 

Tip: 

. 1 <= A.length <= 10000 
-10000 <= A [I] <= 10000 
A has been sorted in non-decreasing order

Method One: Sort

Ideas:

Create a new array, each element of which is a square array corresponding to a given position of the element, then sort the array

public int[] sortedSquares(int[] A) {
     int N = A.length;
     int[] ans = new int[N];
     for (int i = 0; i < N; ++i)
         ans[i] = A[i] * A[i];

     Arrays.sort(ans);
     return ans;
}

The time complexity is O (NlogN);

Space complexity is O (N);

Method two: the double pointer

Ideas:

Because the array  A is already sorted, so it can be said array has a negative value of the square of lined up in descending order, the array has a non-negative value of the square of the ascending lined up.

Using two read pointers are nonnegative part of an array portion and a negative - negative pointer i is read backwards section, the forward pointer j reading non-negative portion.

Using two read pointers are incremented by two of the arrays (sorted by square element). Next, double-pointer technique merge the two arrays.

public int[] sortedSquares(int[] A) {
    int N = A.length;
    int j = 0;
    while (j < N && A[j] < 0)
        j++;
    int i = j-1;

    int[] ans = new int[N];
    int t = 0;

    while (i >= 0 && j < N) {
        if (A[i] * A[i] < A[j] * A[j]) {
             ans[t++] = A[i] * A[i];
             i--;
        } else {
           ans[t++] = A[j] * A[j];
           j++;
        }
    }

    while (i >= 0) {
        ans[t++] = A[i] * A[i];
        i--;
    }
    while (j < N) {
        ans[t++] = A[j] * A[j];
        j++;
    }
    return ans;
}

Time complexity is O (N);

Space complexity is O (N);

Guess you like

Origin www.cnblogs.com/aoeiuvAQU/p/11204854.html