您的位置:首页 > 其它

LeetCode 360. Sort Transformed Array

2016-06-19 11:16 399 查看
/*
Given a sorted array of integers nums and integer values a, b and c.
Apply a function of the form f(x) = ax^2 + bx + c to each element x in
the array. The return array must be in sorted order.
Expected time complexity: O(n)
example:
nums = [-4, -2, 2, 4], a = 1, b = 3, c = 5
result = [3, 9, 15, 33]
*/
#include <vector>
#include <climits>
#include <algorithm>
#include <iostream>
using namespace std;

vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {
vector<int> res;
for(int i = 0; i < nums.size(); ++i) {
int sum = a * nums[i] * nums[i] + b * nums[i] + c;
res.push_back(sum);
}
sort(res.begin(), res.end());
return res;
}
// a variation of merge sort.
vector<int> sortTransformedArrayII(vector<int>& nums, int a, int b, int c) {
vector<int> res;
int minValue = INT_MAX;
int minIndex = 0;
for(int i = 0; i < nums.size(); ++i) {
int tmp = a * nums[i] * nums[i] + b * nums[i] + c;
if(tmp < minValue) {
minValue = tmp;
minIndex = i;
}
}
int front = minIndex;
int end = minIndex + 1;
while(front >= 0 && end < nums.size()) {
int front_value = a * nums[front] * nums[front] + b * nums[front] + c;
int end_value = a * nums[end] * nums[end] + b * nums[end] + c;
if(front_value < end_value) {
res.push_back(front_value);
front--;
} else {
res.push_back(end_value);
end++;
}
}
while(front >= 0) {
int front_value = a * nums[front] * nums[front] + b * nums[front] + c;
res.push_back(front_value);
front--;
}
while(end < nums.size()) {
int end_value = a * nums[end] * nums[end] + b * nums[end] + c;
res.push_back(end_value);
end++;
}
return res;
}

int main(void) {
vector<int> nums {-4, -2, 2, 4};
vector<int> res = sortTransformedArrayII(nums, -1, 3, 5);
for(int i = 0; i < res.size(); ++i) {
cout << res[i] << endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: