Given a sorted integer array nums
and three integers a
, b
and c
, apply a quadratic function of the form f(x) = ax2 + bx + c
to each element nums[i]
in the array, and return the array in a sorted order.
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]
Constraints:
1 <= nums.length <= 200
-100 <= nums[i], a, b, c <= 100
nums
is sorted in ascending order.
Follow up: Could you solve it in O(n)
time?
变换数组排序。
题意是给一个有序数组和几个数字a, b, c 请输出一个新的有序数组满足f(x) = ax^2 + bx + c。
这个题给的公式是初中学的一元二次方程。根据a的正负情况,函数的开口可上可下。这个题的思路依然是two pointer夹逼。因为函数的关系,会导致input数组中最小的和最大的数字在output里面的值也是最小的或者是最大的(取决于a的值)。所以当左右指针从两侧开始遍历input数组的时候,需要判断a的正负情况。如果a为正数,计算结果需要从res的尾部开始摆放;如果a为负数,计算结果需要从res的头部开始摆放。同时根据nums[start]和nums[end]的计算结果,决定到底是start++还是end--。
时间O(n)
空间O(n) - output
JavaScript实现
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 }
Java实现
1 class Solution { 2 public int[] sortTransformedArray(int[] nums, int a, int b, int c) { 3 int[] res = new int[nums.length]; 4 int start = 0; 5 int end = nums.length - 1; 6 int i = a >= 0 ? nums.length - 1 : 0; 7 while (start <= end) { 8 int startNum = getNum(nums[start], a, b, c); 9 int endNum = getNum(nums[end], a, b, c); 10 if (a >= 0) { 11 if (startNum >= endNum) { 12 res[i--] = startNum; 13 start++; 14 } else { 15 res[i--] = endNum; 16 end--; 17 } 18 } else { 19 if (startNum <= endNum) { 20 res[i++] = startNum; 21 start++; 22 } else { 23 res[i++] = endNum; 24 end--; 25 } 26 } 27 } 28 return res; 29 } 30 31 private int getNum(int x, int a, int b, int c) { 32 return a * x * x + b * x + c; 33 } 34 }