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.
我的解法:
两个迭代器,一个从后往前,一个从前往后
vector<int> B;
vector<int>::iterator itb=A.end();
itb--;
for(vector<int>::iterator it=A.begin();it!=itb;){
if(abs(*it)>abs(*itb)){
B.push_back(pow(*it,2));
it++;
}
else
{
B.push_back(pow(*itb,2));
itb--;
}
}
B.push_back(pow(*itb,2));
reverse(B.begin(),B.end());
return B;
高赞解法
简单解法
for(int i = 0; i < A.size(); i++)
{
A[i] = A[i] * A[i];
}
std::sort(A.begin(), A.end());
return A;
我的解法改进
我才知道。。。原来vector是可以像普通数组那样通过下标来访问的。。。所以我为什么每次要通过迭代器呢,查了下迭代器和下标访问的效率,没查到比较准确的说法,还是用下标吧,方便~
//Runtime: 76 ms, faster than 67.87% of C++ online submissions for Squares of a Sorted Array.
//Memory Usage: 2.2 MB, less than 100.00% of C++ online submissions for Squares of a Sorted Array.
class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
int j=A.size()-1;
int i=0;
vector<int> result(j+1);
for(int k=A.size()-1;k>=0;k--){
if(abs(A[i])>abs(A[j])){
result[k]=pow(A[i],2);
i++;
}
else{
result[k]=pow(A[j],2);
j--;
}
}
return result;
}
};