题目描述
给你一个按 非递减顺序 排序的整数数组
nums
,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。示例 1:
输入:nums = [-4,-1,0,3,10] 输出:[0,1,9,16,100] 解释:平方后,数组变为 [16,1,0,9,100] 排序后,数组变为 [0,1,9,16,100]示例 2:
输入:nums = [-7,-3,2,3,11] 输出:[4,9,9,49,121]提示:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
已按 非递减顺序 排序进阶:
- 请你设计时间复杂度为
O(n)
的算法解决本问题
AC代码以及注释
package leetcode_977_Squares_of_a_Sorted_Array;
/**
* @Description: Given an integer array nums sorted in non-decreasing order,
* return an array of the squares of each number sorted in non-decreasing order.
* @Tips: Squaring each element and sorting the new array is very trivial,
* could you find an O(n) solution using a different approach?
*/
class Solution {
public static int[] sortedSquares(int[] nums) {
int leastAbsIndex = 0;
// 寻找nums中绝对值最小的值
// 到了数值为0或者第一个正数就要停止,因为后面的绝对值一定比0或者第一个正数大
while (nums[leastAbsIndex] <= 0 && leastAbsIndex != nums.length - 1 && nums[leastAbsIndex]
* nums[leastAbsIndex + 1] > 0) {
leastAbsIndex++;
}
// 如果leastAbsIndex所指向的位置的值不为0.则要判断左边和右边哪个绝对值比较小
if (leastAbsIndex != nums.length - 1 && nums[leastAbsIndex] != 0) {
leastAbsIndex = Math.abs(nums[leastAbsIndex]) > Math.abs(nums[leastAbsIndex + 1]) ?
leastAbsIndex + 1 : leastAbsIndex;
}
// 现在leastAbsIndex所指向的位置即为nums中绝对值最小的值
int[] retNums = new int[nums.length];
int temp = nums[leastAbsIndex];
int index = 0;
retNums[index++] = temp * temp;
// 左右指针依次寻找当前状态下平方后值最小的值
int leftIndex = leastAbsIndex - 1;
int rightIndex = leastAbsIndex + 1;
while (index < nums.length) {
if (rightIndex >= nums.length || (leftIndex >= 0 &&
nums[leftIndex] * nums[leftIndex] < nums[rightIndex] * nums[rightIndex])) {
retNums[index++] = nums[leftIndex] * nums[leftIndex];
leftIndex--;
} else {
retNums[index++] = nums[rightIndex] * nums[rightIndex];
rightIndex++;
}
}
return retNums;
}
public static void main(String[] args) {
int[] nums = sortedSquares(new int[]{-7, -3, 2, 3, 11});
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i] + " ");
}
}
}
时间以及空间复杂度
-
时间复杂度:O(n),其中 n 是数组长度。执行用时:1 ms,击败 100.00%使用 Java 的用户
-
空间复杂度:O(1),内存消耗:42.68MB,击败 63.60%使用 Java 的用户