Given a sorted array of integers nums and integer values a, b and c. Apply a quadratic function of the form f(x) = _ax_2 + bx + c to each element x in the array.
The function f(x) = ax^2 + bx + c is convex (a > 0) or concave (a < 0). For sorted input, we can use two pointers to fill the result from the correct end, depending on the sign of a.
classSolution {
public: vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {
int n = nums.size();
vector<int> res(n);
auto f = [&](int x) { return a*x*x + b*x + c; };
int l =0, r = n-1, idx = a >=0? n-1:0;
while (l <= r) {
int lv = f(nums[l]), rv = f(nums[r]);
if (a >=0) {
if (lv > rv) res[idx--] = lv, l++;
else res[idx--] = rv, r--;
} else {
if (lv < rv) res[idx++] = lv, l++;
else res[idx++] = rv, r--;
}
}
return res;
}
};
classSolution {
publicint[]sortTransformedArray(int[] nums, int a, int b, int c) {
int n = nums.length;
int[] res =newint[n];
int l = 0, r = n-1, idx = a >= 0 ? n-1 : 0;
while (l <= r) {
int lv = a*nums[l]*nums[l]+ b*nums[l]+ c;
int rv = a*nums[r]*nums[r]+ b*nums[r]+ c;
if (a >= 0) {
if (lv > rv) res[idx--]= lv; else res[idx--]= rv;
if (lv > rv) l++; else r--;
} else {
if (lv < rv) res[idx++]= lv; else res[idx++]= rv;
if (lv < rv) l++; else r--;
}
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
funsortTransformedArray(nums: IntArray, a: Int, b: Int, c: Int): IntArray {
val n = nums.size
val res = IntArray(n)
var l = 0; var r = n-1var idx = if (a >=0) n-1else0funf(x: Int) = a*x*x + b*x + c
while (l <= r) {
val lv = f(nums[l]); val rv = f(nums[r])
if (a >=0) {
if (lv > rv) { res[idx--] = lv; l++ } else { res[idx--] = rv; r-- }
} else {
if (lv < rv) { res[idx++] = lv; l++ } else { res[idx++] = rv; r-- }
}
}
return res
}
}