[LeetCode] Sort Transformed Array 變換數組排序

 

Given a sorted array of integers nums and integer values aband c. Apply a quadratic function of the form f(x) = ax2 + bx + c to each element x in the array.html

The returned array must be in sorted order.java

Expected time complexity: O(n)數組

Example 1:函數

Input: nums = [-4,-2,2,4], a = 1, b = 3, c = 5 Output: [3,9,15,33] 

Example 2:post

Input: nums = [-4,-2,2,4], a = -1, b = 3, c = 5 Output: [-23,-5,1,7]

Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.this

 

這道題給了咱們一個數組,又給了咱們一個拋物線的三個係數,讓咱們求帶入拋物線方程後求出的數組成的有序數組。那麼咱們首先來看O(nlgn)的解法,這個解法沒啥可說的,就是每一個算出來再排序,這裏咱們用了最小堆來幫助咱們排序,參見代碼以下:url

 

解法一:spa

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都填滿。code

當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;
    }
}; 

 

相似題目:

Squares of a Sorted Array

 

參考資料:

https://leetcode.com/problems/sort-transformed-array/

https://leetcode.com/discuss/108831/java-o-n-incredibly-short-yet-easy-to-understand-ac-solution

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索