1. Description:
Notes:
2. Examples:
3.Solutions:
1 /** 2 * Created by sheepcore on 2019-02-12 3 */ 4 class Solution { 5 public int[] sortedSquares(int[] A) { 6 int length = A.length; 7 int[] B = new int[length]; 8 9 // 原数组全为正数 10 if (A[0] >= 0) { 11 for (int i = 0; i < length; i++) 12 B[i] = (int) Math.pow(A[i], 2.0); 13 } 14 15 // 原数组全为负数 16 else if (A[length - 1] < 0) 17 for (int i = 0; i < length; i++) 18 B[i] = (int) Math.pow(A[length - i - 1], 2); 19 else { 20 21 int tail = length - 1; 22 int head = 0, count = 0; 23 int num; 24 // 左右摇摆法找最大绝对值数!然后平方装入数组中。 25 while (head <= tail) { 26 num = A[head]; 27 if (Math.abs(num) > Math.abs(A[tail])) { 28 B[length - count - 1] = (int) Math.pow(num, 2); 29 head++; 30 31 } else { 32 B[length - count - 1] = (int) Math.pow(A[tail], 2); 33 tail--; 34 } 35 count++; 36 } 37 } 38 return B; 39 } 40 }