?LeetCode刷題實戰(zhàn)360:有序轉(zhuǎn)化數(shù)組
Given a sorted array of integers nums and integer values a, band 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)
示例
示例 1:
輸入: nums = [-4,-2,2,4], a = 1, b = 3, c = 5
輸出: [3,9,15,33]
示例 2:
輸入: nums = [-4,-2,2,4], a = -1, b = 3, c = 5
輸出: [-23,-5,1,7]
解題
class Solution {
public:
vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {
vector<int> res(nums.size(),0);
int left=0;
int right=nums.size()-1;
for(int& n:nums){//先計算出各個元素對應(yīng)的值
n=a*n*n+b*n+c;
}
//開口向上
if(a>0){
//從數(shù)組中的較大值從 nums.size()-1 的位置開始,逐個的放入結(jié)果數(shù)組中
int pos=nums.size()-1;
while(left<=right){
if(nums[left]<=nums[right]){
res[pos--]=nums[right--];
}
else{
res[pos--]=nums[left++];
}
}
}
else{
//從數(shù)組中的較小值從 0 的位置開始,逐個的放入結(jié)果數(shù)組中
int pos=0;
while(left<=right){
if(nums[left]<=nums[right]){
res[pos++]=nums[left++];
}
else{
res[pos++]=nums[right--];
}
}
}
return res;//返回結(jié)果
}
};
