Easy
Learn More →
https://leetcode.com/problems/squares-of-a-sorted-array/
#include <vector>
using namespace std;
vector<int> sortedSquaredArray(vector<int> array) {
// Write your code here.
// std::sort is O(nlogn) time
for (auto &x: array){
x *= x;
}
sort(array.begin(), array.end());
return array;
}
#include <vector>
using namespace std;
vector<int> sortedSquaredArray(vector<int> array) {
// Write your code here.
vector<int> squaredArray(array.size(), 0);
int endIdx = array.size() - 1;
int startIdx = 0;
for (int i = array.size() - 1; i >= 0; i--){
if (abs(array[endIdx]) >= abs(array[startIdx])){
squaredArray[i] = array[endIdx]*array[endIdx];
endIdx--;
}else{
squaredArray[i] = array[startIdx]*array[startIdx];
startIdx++;
}
}
return squaredArray;
}
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up