假设我们有一个整数数组和整数值a,b和c的排序数组。我们必须将f(x)= ax ^ 2 + bx + c形式的二次函数应用于数组中的每个元素x。最后的数组必须按排序顺序。
因此,如果输入类似于nums = [-4,-2,2,4],a = 1,b = 3,c = 5,则输出将为[3,9,15,33]
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h> using namespace std; void print_vector(vector<auto< v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: int f(int x, int a, int b, int c){ return a * x * x + b * x + c; } vector<int< sortTransformedArray(vector<int<& nums, int a, int b, int c) { int n = nums.size(); int start = 0; int end = n - 1; vector<int< ret(n); if (a >= 0) { for (int i = n - 1; i >= 0; i--) { int x = f(nums[start], a, b, c); int y = f(nums[end], a, b, c); if (x > y) { start++; ret[i] = x; } else { ret[i] = y; end--; } } } else { for (int i = 0; i < n; i++) { int x = f(nums[start], a, b, c); int y = f(nums[end], a, b, c); if (x < y) { start++; ret[i] = x; } else { ret[i] = y; end--; } } } return ret; } }; main(){ Solution ob; vector<int< v = {-4,-2,2,4}; print_vector(ob.sortTransformedArray(v, 1, 3, 5)); }
{-4,-2,2,4}, 1, 3, 5
输出结果
[3, 9, 15, 33, ]