Leetcode 360 Solution
This article provides solution to leetcode question 360 (sort-transformed-array)
Access this page by simply typing in "lcs 360" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/sort-transformed-array
Solution
class Solution {
public:
int calc(int a, int b, int c, int x)
{
return a * x * x + b * x + c;
}
vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {
int n = nums.size();
vector<int> res(n);
int idx = a >= 0 ? n - 1 : 0;
int l = 0;
int r = n - 1;
while (l <= r)
{
int left_val = calc(a, b, c, nums[l]);
int right_val = calc(a, b, c, nums[r]);
if (a >= 0)
{
if (left_val > right_val)
res[idx--] = left_val, l++;
else
res[idx--] = right_val, r--;
}
else if (a < 0)
{
if (left_val <= right_val)
res[idx++] = left_val, l++;
else
res[idx++] = right_val, r--;
}
}
return res;
}
};