Given a sorted array of integers nums and integer values a, b and c. Apply a quadratic functionof the form f(x) = ax^2 + bx + c to each element x in the array.
The returned array must be in sorted array.
Expected time complexity: O(n)
Example 1:
Input: nums = [-4,-2,2,4], a = 1, b = 3, c = 5
Output: [3,9,15,33]
Example 2:
Input: nums = [-4,-2,2,4], a = -1, b = 3, c = 5
Output: [-23,-5,1,7]
class Solution {
public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
int len = nums.length;
int[] res = new int[len];
if (len == 0) return res;
// Two pointers scan from two ends towards middle
int left = 0, right = len - 1;
int index = a > 0 ? len - 1 : 0;
while (left <= right) {
boolean leftLarger = eval(nums[left], a, b, c) >= eval(nums[right], a, b, c);
if (a > 0) { // starting from end, put larger one
res[index--] = leftLarger ? eval(nums[left++], a, b, c) : eval(nums[right--], a, b, c);
}
else { // starting from front, put smaller one
res[index++] = leftLarger ? eval(nums[right--], a, b, c) : eval(nums[left++], a, b, c);
}
}
return res;
}
private int eval(int x, int a, int b, int c) {
return a * x * x + b * x + c;
}
}