problem
solution
option 1
1 | class Solution { |
option 2 - Two Pointers
利用雙索引,去比較左右索引對應到的數字的平方,比較大小。
1 | class Solution { |
- other version
1
2
3
4
5
6
7
8
9
10vector<int> ret(nums.size(),0);
int l = 0,r = nums.size()-1;
int k =nums.size()-1;
while(l<=r){
if(abs(nums[l])>=abs(nums[r])) ret[k--] =pow(nums[l++],2);
else{
ret[k--] = pow(nums[r--],2);
}
}
return ret;
analysis
- option 1
- time complexity
O(nlogn)
- space complexity
O(1)
- time complexity
- option 2
- time complexity
O(n)
- space complexity
O(1)
- time complexity