有序数组的平方
1. 题目描述
提示
题目链接:https://leetcode.cn/problems/squares-of-a-sorted-array/description/
2. 解题思路
核心总结
- 核心思想:利用数组有序的特性,最大值一定在两端。使用双指针从两边向中间移动,将平方数从大到小依次填入新数组。
💡 易错点
由于要寻找“最大值”,新数组的填充应该从后往前执行。
3. 代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| class Solution {
public int[] sortedSquares(int[] nums) {
int l = 0,r = nums.length - 1;
int point = nums.length - 1;
int[] sq = new int[nums.length];
while(l<=r){
if(square(nums[l])>square(nums[r])){
sq[point] = square(nums[l]);
point--;
l++;
}else{
sq[point] = square(nums[r]);
point--;
r--;
}
}
return sq;
}
private int square(int n) {
return n * n;
}
}
|
4. 复杂度分析
- 时间复杂度:$O(n)$
- 空间复杂度:$O(1)$
5. 总结与反思