思路:
- 找到绝对值最小的坐标,作为起点;将起点的平方值添加到输出数组中,作为第一个数值;
- 双指针,往左往右,双向巡航比较,并且将较小的平方值添加到输出数组中;
- 单指针,将剩余的数字求平方后添加到数组。
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型vector
* @return int整型vector
*/
vector<int> sortedArray(vector<int>& nums) {
// write code here
vector<int> res;
int min_index = 0;
for (int i = 0; i < nums.size() - 1; ++i) {
if (abs(nums[i]) < abs(nums[i+1])) {
min_index = i;
break;
}
}
res.push_back(nums[min_index]*nums[min_index]);
int left = min_index - 1, right = min_index + 1;
while (left >= 0 && right <= nums.size()-1) {
if (abs(nums[left]) <= abs(nums[right])) {
res.push_back(nums[left]*nums[left]);
left--;
}
else {
res.push_back(nums[right]*nums[right]);
right++;
}
}
while (left >= 0) {
res.push_back(nums[left]*nums[left]);
left--;
}
while (right <= nums.size()-1) {
res.push_back(nums[right]*nums[right]);
right++;
}
return res;
}
};



京公网安备 11010502036488号