Square of sorted array
1. Topic
Link to the title of the link
Give you an integer array nums sorted in non-decreasing order , and return a new array composed of the square of each number , which is also required to be sorted in non-decreasing order .
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100]
After sorting, the array becomes is [0,1,9,16,100]
Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]
- 1 <= nums.length <= 104
- -104 <= nums[i] <= 104
- nums is sorted in non-decreasing order
2. Idea
2.1 Violent solution
Square first, then sort
C++ built-in sort() function, sort(first, last, comp), sort range is [first, last)
comp default value is (operator<), you can customize
the default sorting method of bool function as ascending order
The time complexity is: O ( n + n ∗ log ( n ) ) = O ( n ∗ log ( n ) ) O(n+n*log(n)) = O(n*log(n))O ( n+n∗log(n))=O ( n∗log(n))
2.2 Double pointer method
i i The i pointer points tobegin beginbegin, j j The j pointer points toend ende n d
kkk points to the end endof the new arraye n dBecause
the array isan array in non-decreasing order, the element with the maximum value after the square appears at both ends of the array
如果 A [ i ] ∗ A [ i ] < A [ j ] ∗ A [ j ] A[i] * A[i] < A[j] * A[j] A[i]∗A[i]<A [ j ]∗A[j] 那么 r e s u l t [ k − − ] = A [ j ] ∗ A [ j ] ; result[k--] = A[j] * A[j]; result[k−−]=A [ j ]∗A [ j ] ;
如果 A [ i ] ∗ A [ i ] > = A [ j ] ∗ A [ j ] A[i] * A[i] >= A[j] * A[j] A[i]∗A[i]>=A [ j ]∗A[j] 那么 r e s u l t [ k − − ] = A [ i ] ∗ A [ i ] ; result[k--] = A[i] * A[i]; result[k−−]=A[i]∗A[i];
The time complexity is: O ( n ) O(n)O ( n )
3. Code implementation
3.1 Violent solution
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
for(int i = 0; i < nums.size(); i++){
nums[i] *= nums[i];
}
sort(nums.begin(), nums.end());
return nums;
}
};
3.2 Double pointer method
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
// 创建保存返回值的新数组
vector<int> result(nums.size(), 0);
// 数组最后一个位置的index
int k = nums.size() - 1;
// 利用双指针对数组进行遍历,初始化双指针分别指向数组两端
for (int i = 0, j = nums.size() - 1; i <= j; ){
// 注意这里for循环的写法
if(nums[i] * nums[i] < nums[j] * nums[j]){
result[k--] = nums[j] * nums[j];
j--;
}
else{
result[k--] = nums[i] * nums[i];
i++;
}
}
return result;
}
};