变换数组排序。题意是给一个有序数组和几个数字a, b, c 请输出一个新的有序数组满足f(x) = ax^2 + bx + c。例子,
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的正负情况,函数的开口可上可下。这个题的思路依然是two pointer夹逼。因为函数的关系,会导致input数组中最小的和最大的数字在output里面的值也是最小的或者是最大的(取决于a的值)。所以当左右指针从两侧开始遍历input数组的时候,需要判断a的正负情况。如果a为正数,计算结果需要从res的尾部开始摆放;如果a为负数,计算结果需要从res的头部开始摆放。同时根据nums[start]和nums[end]的计算结果,决定到底是start++还是end--。
时间O(n)
空间O(n) - output
1 var sortTransformedArray = function (nums, a, b, c) {
2 let res = new Array(nums.length);
3 let start = 0;
4 let end = nums.length - 1;
5 let i = a >= 0 ? nums.length - 1 : 0;
6 while (start <= end) {
7 let startNum = getNum(nums[start], a, b, c);
8 let endNum = getNum(nums[end], a, b, c);
9 if (a >= 0) {
10 if (startNum >= endNum) {
11 res[i--] = startNum;
12 start++;
13 } else {
14 res[i--] = endNum;
15 end--;
16 }
17 } else {
18 if (startNum <= endNum) {
19 res[i++] = startNum;
20 start++;
21 } else {
22 res[i++] = endNum;
23 end--;
24 }
25 }
26 }
27 return res;
28 };
29
30 var getNum = function (x, a, b, c) {
31 return a * x * x + b * x + c;
32 }
来源:https://www.cnblogs.com/aaronliu1991/p/12381515.html