package com.example.lettcode.dailyexercises;
/**
* @Class SortedSquares
* @Description 977 有序数组的平方
* @Author
* @Date 2020/10/16
**/
public class SortedSquares {
public static int[] sortedSquares(int[] A) {
if (A.length == 0) return new int[]{};
int indexZero = 0;
// 需要考虑下标是否越界
while (indexZero < A.length && A[indexZero] < 0) {
++indexZero;
}
int[] res = new int[A.length];
int index = -1;
int indexL = indexZero - 1;
int indexR = indexZero;
while (indexL >= 0 && indexR < A.length) {
if (Math.abs(A[indexL]) < Math.abs(A[indexR])) {
res[++index] = A[indexL] * A[indexL];
indexL--;
} else {
res[++index] = A[indexR] * A[indexR];
indexR++;
}
}
while (indexL >= 0) {
res[++index] = A[indexL] * A[indexL];
indexL--;
}
while (indexR < A.length) {
res[++index] = A[indexR] * A[indexR];
indexR++;
}
return res;
}
public static void main(String[] args) {
int[] A = new int[]{-7, -3, 2, 3, 11};
int[] ans = sortedSquares(A);
System.out.println("SortedSquares demo01 result:");
for (int num : ans) {
System.out.print("," + num);
}
System.out.println();
A = new int[]{-4, -1, 0, 3, 10};
ans = sortedSquares(A);
System.out.println("SortedSquares demo02 result:");
for (int num : ans) {
System.out.print("," + num);
}
System.out.println();
A = new int[]{-1};
ans = sortedSquares(A);
System.out.println("SortedSquares demo03 result:");
for (int num : ans) {
System.out.print("," + num);
}
}
}