C++ 中对转换后的数组进行排序
假设我们有一个排序好的整数数组 nums 以及整数 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]
为了解决这个问题,我们将遵循以下步骤:
定义函数 f(),它接收 x、a、b、c 作为参数:
返回 ax^2 + bx + c
在主方法中执行以下操作:
n := nums 的大小
start := 0,end := n - 1
定义一个大小为 n 的数组 ret
如果 a >= 0,则:
从 i := n - 1 初始化,当 i >= 0 时,更新 (i 减 1),执行:
x := f(nums[start], a, b, c)
y := f(nums[end], a, b, c)
如果 x > y,则:
(start 加 1)
ret[i] := x
否则
ret[i] := y
(end 减 1)
否则
从 i := 0 初始化,当 i < n 时,更新 (i 加 1),执行:
x := f(nums[start], a, b, c)
y := f(nums[end], a, b, c)
如果 x < y,则:
(start 加 1)
ret[i] := x
否则
ret[i] := y
(end 减 1)
返回 ret
示例
让我们看看以下实现以更好地理解:
#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, ]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP