Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
原文链接:https://leetcode.com/problems/squares-of-a-sorted-array/
比较简单,给一个非递减的数组,数组中的数字有正也有负,然后需要把数组中的数字取平方并且从小到大进行排序并返回。
最简单的做法就是把数组中的所有数字取平方,然后对这个数组进行排序并返回。但是这样的话,就会对数组遍历两次(取平方一次,排序一次),明显效率不太高。
class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
for(int i = 0; i < A.size(); i++) {
A[i] *= A[i];// 平方
}
sort(A.begin(), A.end());
return A;
}
};
可以看到题目中说的数组是非递减的,这样看来最大的数在数组的最后面,那么最大的数平方之后也会是最大的,但是不要忘记了很小的负数平方之后也会有可能变成最大的,比如:- 9 的平方 = 81 > 8 的平方 = 64。
所以平方之后最大的数可能是在原数组的最前面(负数),也有可能是在原数组的最后面(正数),根据此特性,只需遍历一边数组即可。我们从原数组的两侧开始遍历,把平方之后较大的数放在新数组的最后,依次向中间靠拢计算即可。
// 利用非递减的特性
class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
int left = 0;
int right = A.size() - 1;
int n = A.size() - 1;
vector<int> result(A.size(), 0); // 用来保存平方之后的数组
while(left <= right) { // 平方最大的数字在数组的两侧
if(abs(A[left]) < abs(A[right]))
result[n--] = A[right]*A[right--];
else
result[n--] = A[left]*A[left++];
}
return result;
}
};