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; } }
相关文章推荐
- 【Debug】双击cpp文件无法直接打开,提示“向程序发送命令时出现问题”
- code1174 靶形数独
- Linux 驱动面试题总结
- 数组中只出现一次的数字41
- 【.net 深呼吸】写入日志文件
- hdu 4504(动态规划)
- git - 简易指南
- 开源年中国(五)清除缓存
- 善于利用win7系统自带sysprep工具重置系统的方法 (去SID)
- GIT使用教程与基本原理
- WLW离线编辑器的安装与使用
- ajax调后台servlet,把返回json用vue做绑定
- 罗马数字转换成整数
- 网站收藏
- Linux 下的DMA浅析
- 第十六周学习进度表
- Increasing Triplet Subsequence
- 第四专题 Problem E
- Git基础使用教程:第一个Git项目
- 【南理oj】8 - 一种排序(优先队列)