Given a sorted array of integers nums and integer values a, b and c. Apply a quadratic function of the form f(x) = ax2 + bx + c to each element x in the array.
The returned array must be in sorted order.
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]
思路:这个方程是个二次方程,也就是个椭圆,那么a > 0的时候,是U型,a < 0 是N型,
也就是如果是U型,那么就是两头大,中间小,那么我result 从最后index = n - 1开始累积,i, j 相向而行,
N型就是两边小,中间大。那么我result从最小开始累积,index = 0开始累加;i, j 相向而行,
这题可以跟 Squares of a Sorted Array 一起复习;
class Solution {
public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
if(nums == null || nums.length == 0) {
return new int[0];
}
int n = nums.length;
int i = 0; int j = n - 1;
int index = a >= 0 ? n - 1 : 0;
int[] res = new int[n];
while(i <= j) {
if(a >= 0) {
res[index--] = fx(a, b, c, nums[i]) >= fx(a, b, c, nums[j])
? fx(a, b, c, nums[i++]) : fx(a, b, c, nums[j--]);
} else {
res[index++] = (fx(a, b, c, nums[i]) <= fx(a, b, c, nums[j]))
? fx(a, b, c, nums[i++]) : fx(a, b, c, nums[j--]);
}
}
return res;
}
private int fx(int a, int b, int c, int x) {
return a * x * x + b * x + c;
}
}