您的位置:首页 > 其它

Sort Transformed Array -- LeetCode

2016-08-25 12:37 375 查看
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]


思路:因为是排好序的数组,我们用两个指针从数组两边向中间计算答案。根据每次计算的函数值的大小决定移动哪个指针。复杂度O(N)。

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 len = nums.size();
vector<int> res(len);
int left = 0, right = nums.size() - 1, count = 0;
while (left <= right) {
int leftRes = f(nums[left], a, b, c);
int rightRes = f(nums[right], a, b, c);
bool goLeft = (a >= 0 && leftRes >= rightRes) || (a < 0 && leftRes <= rightRes);
int curPos = (a >= 0 ? len - 1 - count : count);
if (goLeft) {
res[curPos] = leftRes;
left++;
} else {
res[curPos] = rightRes;
right--;
}
count++;
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: