三、977.有序数组的平方
题解参考代码随想录
1. 题目描述
给你一个按 非递减顺序 排序的整数数组
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) 的算法解决本问题
2. 解题思路
这道题大致有两种思路
- 思路一:先对原数组进行平方,再对平方之后的数组进行排序,返回数组即可,时间复杂度
O(nlogn)
- 思路二:使用双指针法,时间复杂度为
O(n)
3. 暴力解法
由于这里考察的重点不是排序算法,所以这里我们直接调用了C++的sort
函数,对平方后的数组排序。
代码如下所示
/**
* 时间复杂度:O(nlogn)
*/
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
// 将数组的所有元素平方
for (int i = 0; i < nums.size(); i++) {
nums[i] *= nums[i];
}
// 调用快排
sort(nums.begin(), nums.end());
// 返回数组
return nums;
}
};
- 时间复杂度:
O(nlogn)
- 空间复杂度:
O(1)
4. 双指针法
注意:数组其实是有序的,并且数组中的元素有正有负,所以数组平方的最大值就在数组的两端,不是最左边就是最右边,不可能是中间。
此时我们可以考虑双指针法,left指向起始位置,right指向终止位置。
定义一个新数组ans,和nums数组一样的大小,让index指向ans数组终止位置。
- 如果
nums[left] * nums[left] <= nums[right] * nums[right]
,那么ans[index--] = nums[right] * nums[right];
。 - 如果
nums[left] * nums[left] > nums[right] * nums[right]
,那么ans[index--] = nums[left] * nums[left];
。
代码如下所示
/**
* Note: The returned array must be malloced, assume caller calls free().
* 时间复杂度:O(n)
* 空间复杂度:O(1)
*/
int* sortedSquares(int* nums, int numsSize, int* returnSize){
// 新数组大小就是原数组的大小
*returnSize = numsSize;
// 定义左右指针
int left = 0;
int right = numsSize - 1;
// 开辟新数组空间
int *ans = (int *)malloc(sizeof(int) * numsSize);
for (int index = numsSize - 1; index >=0; index--) {
// 左指针指向元素的平方
int lSquare = nums[left] * nums[left];
// 右指针指向元素的平方
int rSquare = nums[right] * nums[right];
// 如果左平方大于右平方
if (lSquare > rSquare) {
// 将左放入新数组中
ans[index] = lSquare;
// 更新左指针
left++;
} else {
// 如果右平方大于等于左平方,将右放入新数组
ans[index] = rSquare;
// 更新右指针
right--;
}
}
// 返回新数组
return ans;
}
注意:这里我们需要自己定义一个返回数组,并且指定返回数组的大小returnSize
- 时间复杂度:
O(n)
- 空间复杂度:
O(1)
5. 总结
这道题本身的代码并不复杂,只要注意原数组是有序的,并且数组元素有正有负,那么平方之后的元素最大值一定在左右两端,那么很容易就想到使用双指针法遍历数组。