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