给你一个sorted Integer array,输出sorted array consisted of squares of input integers,比如[1,3,5] -> [1,9,25]
[-3, -1, 0,
1, 2] -> [0, 1, 1, 4, 9]
package array;
public class SortSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] array = { -5, -3, 0, 1, 6 };
int[] res = square1(array);
for (int i : res) {
System.out.println(i);
}
}
public static int[] square1(int[] nums) {
if (nums == null || nums.length == 0)
return new int[0];
int left = 0, right = nums.length - 1, index = right;
int[] res = new int[nums.length];
while (left <= right) {
if (Math.abs(nums[left]) >= Math.abs(nums[right])) {
res[index--] = nums[left] * nums[left];
left++;
} else {
res[index--] = nums[right] * nums[right];
right--;
}
}
return res;
}
}