977. 有序数组的平方
问题977 有序数组的平方 ★☆☆☆☆
https://leetcode-cn.com/problems/squares-of-a-sorted-array/
如何以O(N)的时间复杂度来解决这个问题呢?我一开始的思路是先遍历到第一个正数的位置,然后从该位置向两边遍历。看了下官方题解才明白,直接从两端向中间遍历就可以嘛。很好的体现了双指针的概念。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public int[] sortedSquares(int[] nums) {
assert nums.length > 0;
int len = nums.length;
int[] squares = new int[len];
int i = 0, j = len - 1, k = len - 1;
while (i <= j) {
if (Math.abs(nums[i]) >= Math.abs(nums[j])) {
squares[k--] = nums[i] * nums[i];
i++;
} else {
squares[k--] = nums[j] * nums[j];
j--;
}
}
return squares;
}
本文由作者按照 CC BY 4.0 进行授权