package com.zmz.algorithm.array;
import java.util.Arrays;
/**
* @author 张明泽
* Create by 2022/5/23 9:30
* 有序数组的平方
* LeetCode-977
*/
public class ArraySquare {
public static void main(String[] args) {
int[] arr = {-4,-1,0,3,10};
int[] result = sortArraySquare(arr);
System.out.println(Arrays.toString(result));
}
public static int[] sortArraySquare(int[] arr) {
int[] numbers = new int[arr.length];
int left = 0;
int right = arr.length - 1;
int index = arr.length - 1;
while (left <= right) {
if (arr[left] * arr[left] <= arr[right] * arr[right]) {
numbers[index--] = arr[right] * arr[right];
--right;
} else {
numbers[index--] = arr[left] * arr[left];
++left;
}
}
return numbers;
}
}
最后修改:2022 年 05 月 25 日 12 : 17 PM
© 允许规范转载