0977.cpp (981B)
1 // Intuitive solution 2 class Solution { 3 public: 4 vector<int> sortedSquares(vector<int> &nums) { 5 vector<int> res; 6 int i = 0, j = nums.size() - 1; 7 while (i <= j) { 8 int n1 = nums[i] * nums[i]; 9 int n2 = nums[j] * nums[j]; 10 if (n1 > n2) { 11 res.push_back(n1); 12 i++; 13 } else { 14 res.push_back(n2); 15 j--; 16 } 17 } 18 reverse(res.begin(), res.end()); 19 return res; 20 } 21 }; 22 23 // Intuitive solution, better execution 24 // avoids recomputation of squares 25 // avoids reversal of the array 26 class Solution { 27 public: 28 vector<int> sortedSquares(vector<int> &nums) { 29 int n = nums.size(), i = 0, j = nums.size() - 1; 30 vector<int> res(n); 31 for_each(nums.begin(), nums.end(), [](int &a) { a *= a; }); 32 while (i <= j) 33 res[--n] = nums[i] > nums[j] ? nums[i++] : nums[j--]; 34 return res; 35 } 36 };