Leetcode 977. Squares of a Sorted Array
Given an integer array nums
sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
nums = [-4, -1, 0, 3, 10]
[0, 1, 9, 16, 100]
#include <vector>
#include <algorithm>
std::vector<int> sortedSquares(std::vector<int>& nums) {
int n = nums.size();
std::vector<int> result(n);
int left = 0;
int right = n - 1;
int position = n - 1;
while (left <= right) {
if (abs(nums[left]) > abs(nums[right])) {
result[position] = nums[left] * nums[left];
left++;
} else {
result[position] = nums[right] * nums[right];
right--;
}
position--;
}
return result;
}
The time complexity of this solution is O(n), where n
is the length of the input array. This is because we are processing each element of the array exactly once.
The space complexity is also O(n), where n
is the size of the input array, as we are utilizing an additional array of the same size to store the result.
By using the two pointers technique, we are able to achieve a solution that processes the array in linear time while avoiding the need to sort the resultant array separately.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?