LeetCode 360. Sort Transformed Array

来源:互联网 发布:怎么联系网络运营商 编辑:程序博客网 时间:2024/06/05 16:56
/*  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;  }}

0 0
原创粉丝点击