问题描述:
给你一个按 非递减顺序 排序的整数数组 nums
,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
示例 1:
输入:nums = [-4,-1,0,3,10] 输出:[0,1,9,16,100] 解释:平方后,数组变为 [16,1,0,9,100] 排序后,数组变为 [0,1,9,16,100]
问题讨论:
由于初始数组按非递减顺序排序,因此最左侧和最右侧具有最大的正数和负数的绝对值。你可以初始化两个指针分别指向最左侧和最右侧,不断比较它们的值,并将其插入到解决方案向量中。需要注意的是,插入的顺序需要从末尾到开头,因为题目要求返回的结果也要按非递减顺序排列。
我的实现:
在我的实现中,我使用了两个指针 start
和 end
,分别指向数组的开头和结尾。通过比较 nums[start]
和 nums[end]
的绝对值大小,将较大的值存储在临时向量 v
中。然后,从 v
的末尾到开头遍历,将每个元素的平方值依次插入到结果向量 sol
中。最后返回 sol
作为最终的结果。
需要注意的是,临时向量 v
的使用是不必要的,可以直接从末尾到开头将元素的平方值插入到 sol
中,这样可以节省额外的空间。
English version:
Problem Discussion:
Since the initial array is sorted in non-descending order, the leftmost and rightmost elements have the largest absolute values of positive and negative numbers. You can initialize two pointers pointing to the leftmost and rightmost elements and compare their values, inserting them into the solution vector. It's important to note that the order of insertion should be from the end to the beginning because the problem requires the result to be returned in non-decreasing order as well.
My Implementation:
In my implementation, I used two pointers start
and end
pointing to the beginning and end of the array, respectively. By comparing the absolute values of nums[start]
and nums[end]
, the larger value is stored in a temporary vector v
. Then, iterating from the end to the beginning of v
, the square of each element is inserted into the result vector sol
. Finally, sol
is returned as the final result.
It's worth noting that the use of the temporary vector v
is unnecessary. Instead, you can directly insert the squares of the elements into sol
from the end to the beginning, which saves extra space.
#include <vector>
#include <algorithm>
#include <iostream>
#include <cmath>
using namespace std;
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
if (nums.size() == 0) return nums;
int start = 0, end = nums.size() -1;
vector<int> v;// unnecessary, can direct push_back to sol from the end to start
vector<int> sol;
while (end >= start) {
bool b = abs(nums[start]) > abs(nums[end]);
int big = b ? abs(nums[start]) : abs(nums[end]);
v.push_back(big);
if (b) start++;
else end--;
}
/*for (auto i : v) {
cout << i << " ";
}*/
for (int i = v.size() - 1; i >= 0; i--) {
sol.push_back(v[i] * v[i]);
}
return sol;
}
};