1.题目:​​https://leetcode-cn.com/problems/squares-of-a-sorted-array/​

2.思路

(1)用sort,过于简单了
(2)归并排序的思想

3.代码

https://leetcode-cn.com/problems/squares-of-a-sorted-array/solution/yong-gui-bing-si-xiang-ji-ke-by-daniel_shwei/
方法1:
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;
}
};

方法2:
class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
int leth=A.size();
int i=0,j=leth-1,k=leth;
vector<int> B(leth);
while (k>0)
{
int x=A[i]*A[i];
int y=A[j]*A[j];
if (x>y)
{
B[--k]=x;
i++;
}
else
{
B[--k]=y;
j--;
}
}
return B;
}
};

改进方法2
class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
int leth=A.size()-1;
int i=0,j=leth,k=leth;
vector<int> B(leth+1);
while (k>=0)
{
int x=A[i]*A[i];
int y=A[j]*A[j];
if (x>y)
{
B[k--]=x;
i++;
}
else
{
B[k--]=y;
j--;
}
}
return B;
}
};