暴力解法
调用sort函数
#include <iostream> #include <vector> #include<algorithm> using namespace std; class Solution { public: vector<int> sortedSquares(vector<int>& nums) { vector<int> result; int temp = 0; for (int i = 0; i < nums.size(); i++) { result.push_back (nums[i] * nums[i]); } sort(result.begin() , result.end()); return result; } }; int main() { Solution a; vector<int> num = { -4,-1,0,3,10 }; vector<int> sum; sum = a.sortedSquares(num); for (int i=0; i < sum.size(); i++) { cout << sum[i] << ' '; } cout << endl; return 0; }
双指针
#include <iostream> #include <vector> #include<algorithm> using namespace std; class Solution { public: vector<int> sortedSquares(vector<int>& nums) { vector<int> result(nums.size(),0); int i = 0, j = nums.size() - 1 ,member =nums.size() - 1; while( i <= j) { if (nums[i] * nums[i] > nums[j] * nums[j]) { result[member--] = nums[i] * nums[i]; i++; } else { result[member--] = nums[j] * nums[j]; j--; } } return result; } }; int main() { Solution a; vector<int> num = { -4,-1,0,3,10 }; vector<int> sum; sum = a.sortedSquares(num); for (int i=0; i < sum.size(); i++) { cout << sum[i] << ' '; } cout << endl; return 0; }
二刷
库函数
class Solution { public: vector<int> sortedSquares(vector<int>& nums) { for(int i=0 ;i<nums.size();i++) { nums[i] = pow(nums[i],2);; } sort(nums.begin(),nums.end()); return nums; } };
双指针
class Solution { public: vector<int> sortedSquares(vector<int>& nums) { int left=0 ,right = nums.size()-1; vector<int> result; while(left<=right) { if( pow(nums[left],2) >= pow(nums[right],2) ) { result.insert(result.begin() , pow(nums[left],2) ); left++; }else { result.insert(result.begin() , pow(nums[right],2) ); right--; } } return result; } };