[LeetCode] Sort Transformed Array

360. Sort Transformed Array

Given a sorted integer array nums and three integers a, b and c, apply a quadratic function of the form f(x) = ax2 + bx + c to each element nums[i] in the array, and return the array in a sorted order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
int transform(int n, int a, int b, int c) {
return a * n * n + b * n + c;
}
public:
vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {
int l = 0, r = nums.size() - 1;
int index = a >= 0 ? r : l;
vector<int> res(r+1);

while(l <= r) {
int left = transform(nums[l], a, b, c), right = transform(nums[r], a, b, c);
if(a >= 0) {
res[index--] = max(left, right);
if(left > right) l++;
else r--;
} else {
res[index++] = min(left, right);
if(left < right) l++;
else r--;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/21/PS/LeetCode/sort-transformed-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.