LeetCode刷题实战360:有序转化数组
共 4932字,需浏览 10分钟
·
2021-08-24 17:27
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){//先计算出各个元素对应的值
n=a*n*n+b*n+c;
}
//开口向上
if(a>0){
//从数组中的较大值从 nums.size()-1 的位置开始,逐个的放入结果数组中
int pos=nums.size()-1;
while(left<=right){
if(nums[left]<=nums[right]){
res[pos--]=nums[right--];
}
else{
res[pos--]=nums[left++];
}
}
}
else{
//从数组中的较小值从 0 的位置开始,逐个的放入结果数组中
int pos=0;
while(left<=right){
if(nums[left]<=nums[right]){
res[pos++]=nums[left++];
}
else{
res[pos++]=nums[right--];
}
}
}
return res;//返回结果
}
};