题目链接:有序数组的平方
关键点:
【1】原数组是按照非递减顺序排序的整数数组;
【2】平方后的新数组也是按照非递减的顺序排序。
思路:
暴力解法:遍历数组,将每个数组元素平方后,按照从小到大进行排序。
双指针解法:定义一个和原数组大小相同的新数组,使用一个指针指向该数组最后一个元素的位置。然后定义左右指针分别从原数组的左右两端向中间移动,每次取最大值从新数组最后位置依次向前填入。
1)暴力解法
#include <iostream>
#include <vector>
#include <algorithm>
class Solution
{
public:
std::vector<int> sortedSquares(std::vector<int>& nums)
{
for (int i = 0; i < nums.size(); ++i) // 遍历数组元素,将每个元素进行平方
{
nums[i] *= nums[i];
}
std::sort(nums.begin(), nums.end()); // 对平方后的数组进行排序,这里的sort为STL中排序函数类似快排
return nums;
}
};
int main()
{
std::vector<int> nums = { -1,-2,-3,0,1,3,4,8,7 };
Solution s;
std::vector<int> vecRet = s.sortedSquares(nums);
for (int i = 0; i < nums.size(); ++i)
{
std::cout << vecRet[i] << std::endl;
}
return 0;
}
2) 双指针解法
#include <iostream>
#include <vector>
#include <algorithm>
class Solution
{
public:
std::vector<int> sortedSquares(std::vector<int>& nums)
{
std::vector<int> newnums(nums.size(), 0); // 定义一个与原数组大小相同的新数组,并全部初始化为0
int pos = newnums.size() - 1; // 指向新数组最后一个可填入位置
int left = 0; // 指向原数组第一个位置
int right = nums.size() - 1; // 指向新数组最后一个位置
while (left <= right) // left <= right,最后一个元素必定是left和right同时指向
{
// 每次取左右两个元素中的最大值填入新数组,并更新左右位置和新数组的可填入位置
if (nums[left] * nums[left] < nums[right] * nums[right]) // left^2<right^2
{
// right^2 赋给新数组,新数组可填入位置向前移动一位,原数组右位置向前移动一位
newnums[pos--] = nums[right] * nums[right];
right--;
}
else
{
// left^2 赋给新数组,新数组可填入位置向前移动一位,原数组左位置向后移动一位
newnums[pos--] = nums[left] * nums[left];
left++;
}
}
return newnums;
}
};
int main()
{
std::vector<int> nums = { -1,-2,-3,0,1,3,4,8,7 };
Solution s;
std::vector<int> vecRet = s.sortedSquares(nums);
for (int i = 0; i < nums.size(); ++i)
{
std::cout << vecRet[i] << std::endl;
}
return 0;
}