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:
思路:因为是排好序的数组,我们用两个指针从数组两边向中间计算答案。根据每次计算的函数值的大小决定移动哪个指针。复杂度O(N)。
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; } };
相关文章推荐
- Leetcode 360 Sort Transformed Array
- LeetCode 360. Sort Transformed Array
- [Leetcode] 360. Sort Transformed Array 解题报告
- [LeetCode] 360. Sort Transformed Array 排序转换后的数组
- [LeetCode] Sort Transformed Array 变换数组排序
- Leetcode: Sort Transformed Array
- LeetCode 360. Sort Transformed Array
- LeetCode 360. Sort Transformed Array
- [leetcode] 360. Sort Transformed Array 解题报告
- LeetCode 360. Sort Transformed Array(计算函数)
- 360. Sort Transformed Array
- Sort Transformed Array
- LeetCode88 Merge two sort array
- leetcode media of an sort array
- Sort Transformed Array
- Sort Transformed Array
- leetcode.array--75. Sort Colors
- 【leetcode】Array——Sort Color(75)
- 【LeetCode】【Array】【75】Sort Colors
- LeetCode刷题【Array】 Sort Colors