[LeetCode] 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:
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]
Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.
這道題給了我們一個數組,又給了我們一個拋物線的三個係數,讓我們求帶入拋物線方程後求出的陣列成的有序陣列。那麼我們首先來看O(nlgn)的解法,這個解法沒啥可說的,就是每個算出來再排序,這裡我們用了最小堆來幫助我們排序,參見程式碼如下:
解法一:
class Solution { public: vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) { vector<int> res; priority_queue<int, vector<int>, greater<int>> q; for (auto d : nums) { q.push(a * d * d + b * d + c); } while (!q.empty()) { res.push_back(q.top()); q.pop(); }return res; } };
但是題目中的要求讓我們在O(n)中實現,那麼我們只能另闢蹊徑。其實這道題用到了大量的高中所學的關於拋物線的數學知識,我們知道,對於一個方程f(x) = ax2 + bx + c 來說,如果a>0,則拋物線開口朝上,那麼兩端的值比中間的大,而如果a<0,則拋物線開口朝下,則兩端的值比中間的小。而當a=0時,則為直線方法,是單調遞增或遞減的。那麼我們可以利用這個性質來解題,題目中說明了給定陣列nums是有序的,如果不是有序的,我想很難有O(n)的解法。正因為輸入陣列是有序的,我們可以根據a來分情況討論:
當a>0,說明兩端的值比中間的值大,那麼此時我們從結果res後往前填數,用兩個指標分別指向nums陣列的開頭和結尾,指向的兩個數就是拋物線兩端的數,將它們之中較大的數先存入res的末尾,然後指標向中間移,重複比較過程,直到把res都填滿。
當a<0,說明兩端的值比中間的小,那麼我們從res的前面往後填,用兩個指標分別指向nums陣列的開頭和結尾,指向的兩個數就是拋物線兩端的數,將它們之中較小的數先存入res的開頭,然後指標向中間移,重複比較過程,直到把res都填滿。
當a=0,函式是單調遞增或遞減的,那麼從前往後填和從後往前填都可以,我們可以將這種情況和a>0合併。
解法二:
class Solution { public: vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) { int n = nums.size(), i = 0, j = n - 1; vector<int> res(n); int idx = a >= 0 ? n - 1 : 0; while (i <= j) { if (a >= 0) { res[idx--] = cal(nums[i], a, b, c) >= cal(nums[j], a, b, c) ? cal(nums[i++], a, b, c) : cal(nums[j--], a, b, c); } else { res[idx++] = cal(nums[i], a, b, c) >= cal(nums[j], a, b, c) ? cal(nums[j--], a, b, c) : cal(nums[i++], a, b, c); } } return res; } int cal(int x, int a, int b, int c) { return a * x * x + b * x + c; } };
參考資料: