Given a sorted array of integers nums and integer values a, b and c. Apply a 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:
nums = [-4, -2, 2, 4], a = 1, b = 3, c = 5, Result: [3, 9, 15, 33] nums = [-4, -2, 2, 4], a = -1, b = 3, c = 5 Result: [-23, -5, 1, 7] 分析:
抛物线的中轴线可以通过-b/2a来计算,这题可以转换成按照各个点到中轴线的距离依次排列。所以,我们先找到距离中轴线最近的点 p ,然后,设置两个pointer,从p开始,一个向左走,一个向右走。看两个Pointer对应的值哪个离中轴线更近,然后取近的一个,同时移动对应的pointer. 后来发现有更好的方法,也是使用两个pointer,一个指向最左边,一个指向最右边。然后谁离中轴线越远,就选谁。 https://discuss.leetcode.com/topic/48424/java-o-n-incredibly-short-yet-easy-to-understand-ac-solution
public class Solution {
public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
int n = nums.length;
int[] sorted = new int[n];
int i = , j = n - ;
int index = a >= ? n - : ;
while (i <= j) {
if (a >= ) {
sorted[index--] = quad(nums[i], a, b, c) >= quad(nums[j], a, b, c) ? quad(nums[i++], a, b, c) : quad(nums[j--], a, b, c);
} else {
sorted[index++] = quad(nums[i], a, b, c) >= quad(nums[j], a, b, c) ? quad(nums[j--], a, b, c) : quad(nums[i++], a, b, c);
}
}
return sorted;
} private int quad(int x, int a, int b, int c) {
return a * x * x + b * x + c;
}
}