class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int l=nums.size()-1;
int x=l;
for(int i=0;i<l;i++)
{
if(nums[i+1]>0)
{
x=i;
break;
}
}
int nr;
int nl;
int lx=x;
int lr=x+1;
vector<int>n;
while(lx>=0||lr<=l)
{
if(lr<=l)
{
nr=nums[lr]*nums[lr];
}
if(lx>=0)
{
nl=nums[lx]*nums[lx];
}
if((nr>=nl&&lx>=0)||lr>l)
{
n.push_back(nl);
lx--;
}
else
{
n.push_back(nr);
lr++;
}
}
return n;
}
};
看到题目的第一想法是用遍历,不过因为是算法范围的题,要求用双指针,就写了双指针。
没注意时间,不过作为简单题应该是慢了。
内存消耗有点大。
加油!
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
vector<int> ans;
for (int num: nums) {
ans.push_back(num * num);
}
sort(ans.begin(), ans.end());
return ans;
}
};
结果答案里的遍历好像时间复杂度更低嘞。