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]
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A is sorted in non-decreasing order.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
跟刚才那道题很像,找到一个神奇思路,两边的平方一定是最大的,so~双指针从两边往中间移动就很简单了,一开始从中间往两边走就麻烦很多
但是这个时间速度很慢~百分之23%
class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
int n=A.size();
vector<int> num(n);
if(n==0){
return num;
}
int a=0;
int b=n-1;
int na,nb;
while(n>0&&a!=b){
n--;
na=A[a]*A[a];
nb=A[b]*A[b];
if(na>nb){
a++;
num[n]=na;
}else{
b--;
num[n]=nb;
}
}
if(n>0) num[0]=A[a]*A[a];
return num;
}
};
暴力的老哥都比我快
class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
//暴力求解 双指针
int start =0,end=A.size()-1;
vector<int> res;
while(start<=end){
if(abs(A[start])>abs(A[end])){
res.push_back(A[start]*A[start]);
start++;
}else{
res.push_back(A[end]*A[end]);
end--;
}
}
reverse(res.begin(),res.end());
return res;
}
};