给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。
示例 1:
输入:[-4,-1,0,3,10]
输出:[0,1,9,16,100]
示例 2:
输入:[-7,-3,2,3,11]
输出:[4,9,9,49,121]
class Solution {
public static int[] sortedSquares(int[] A) {
int length = A.length;
//新数组,未排序
int[] b = new int[length];
//求平方
for(int i = 0;i<length;i++){
b[i] = A[i] * A[i];
}
//中间量
int temp;
//从小到大输出
b = selectSort(b);
return b;
}
public static int[] selectSort(int[] array){
int length = array.length;
//找出最小下标
for(int i = 0;i<length-1;i++) {
//最小下标
int minIndex = i;
for (int j = i+1; j < length; j++) {
//跟最小下标对应数比较
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
//将找到的最小值和i位置所在的值进行交换
if (i != minIndex) {
int tmp = array[i];
array[i] = array[minIndex];
array[minIndex] = tmp;
}
}
return array;
}
}