题目描述:
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]
class Solution {
public:
vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {
// ax^2+bx+c=a(x+bx/2a)^2+c-b^2/4a,对称轴是-b/2a
// 所以当a大于等于0时,定义两个指针往中间移动,依次把结果放入数组末尾
// a小于0时,定义两个指针往中间移动,依次把结果放入数组开头
int n=nums.size();
vector<int> result(n);
int i=0, j=n-1;
int count=0;
while(i<=j)
{
int x=a*nums[i]*nums[i]+b*nums[i]+c;
int y=a*nums[j]*nums[j]+b*nums[j]+c;
if(a>=0)
{
if(x>y) result[n-1-count]=x, i++;
else result[n-1-count]=y, j--;
}
else
{
if(x>y) result[count]=y, j--;
else result[count]=x, i++;
}
count++;
}
return result;
}
};