[leetcode] 360. Sort Transformed Array 解题报告
2016-06-17 16:17
477 查看
题目链接: https://leetcode.com/problems/sort-transformed-array/
Given a sorted array of integers nums and integer values a, b and c. Apply a function of the form f(x) = ax2 + bx + c to
each element x in the array.
The returned array must be in sorted order.
Expected time complexity: O(n)
Example:
思路: 当a>0时,抛物线开口向上,这样给定的数组最大值肯定是在两端, 也就是要么在数组开始,要么在数组的最后, 这样我们可以依次取得最大值.最后的时候翻转一下数组即可.
当a<0时, 抛物线开口向下,这样最小值肯定也是在两端, 我们可以依次在两端取最小值.
代码如下:
class Solution {
public:
vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {
if(nums.size() ==0) return {};
vector<int> result;
int left = 0, right = nums.size()-1;
auto func = [=](int x) { return a*x*x + b*x + c; };
while(left <= right)
{
int val1 = func(nums[left]), val2 = func(nums[right]);
if(a > 0) result.push_back(val1>=val2?val1:val2);
if(a > 0) val1>val2?left++:right--;
if(a <= 0) result.push_back(val1>=val2?val2:val1);
if(a <= 0) val1>val2?right--:left++;
}
if(a > 0) reverse(result.begin(), result.end());
return result;
}
};
Given a sorted array of integers nums and integer values a, b and c. Apply a function of the form f(x) = ax2 + bx + c to
each element x in the array.
The returned 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] nums = [-4, -2, 2, 4], a = -1, b = 3, c = 5 Result: [-23, -5, 1, 7]
思路: 当a>0时,抛物线开口向上,这样给定的数组最大值肯定是在两端, 也就是要么在数组开始,要么在数组的最后, 这样我们可以依次取得最大值.最后的时候翻转一下数组即可.
当a<0时, 抛物线开口向下,这样最小值肯定也是在两端, 我们可以依次在两端取最小值.
代码如下:
class Solution {
public:
vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {
if(nums.size() ==0) return {};
vector<int> result;
int left = 0, right = nums.size()-1;
auto func = [=](int x) { return a*x*x + b*x + c; };
while(left <= right)
{
int val1 = func(nums[left]), val2 = func(nums[right]);
if(a > 0) result.push_back(val1>=val2?val1:val2);
if(a > 0) val1>val2?left++:right--;
if(a <= 0) result.push_back(val1>=val2?val2:val1);
if(a <= 0) val1>val2?right--:left++;
}
if(a > 0) reverse(result.begin(), result.end());
return result;
}
};
相关文章推荐
- 微软Word 2007数学插件 Microsoft Math 提供下载
- 关于C# Math 处理奇进偶不进的实现代码
- JavaScript Math 对象常用方法总结
- JavaScript中的Math.SQRT1_2属性使用简介
- JavaScript Math.ceil() 函数使用介绍
- 与Math.pow 相反的函数使用介绍
- JavaScript中使用指数方法Math.exp()的简介
- JavaScript使用Math.Min返回两个数中较小数的方法
- Ajax获取页面被缓存的解决方法
- JavaScript高级程序设计 阅读笔记(十二) js内置对象Math
- JavaScript中Math对象使用说明
- javascript对象之内置对象Math使用方法
- 基于java math API 的详细解释说明
- 简介JavaScript中用于处理正切的Math.tan()方法
- 浅谈JavaScript中的Math.atan()方法的使用
- PHP内置的Math函数效率测试
- 在JavaScript中使用对数Math.log()方法的教程
- JavaScript中用于四舍五入的Math.round()方法讲解
- Javascript之Math对象详解
- 简介JavaScript中Math.LOG10E属性的使用