Sort Transformed Array

Given a sorted array of integers nums and integer values ab and c. Apply a quadratic 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 1:

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

Example 2:

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

思路:這個方程是個二次方程,也就是個橢圓,那麼a > 0的時候,是U型,a < 0 是N型,

也就是如果是U型,那麼就是兩頭大,中間小,那麼我result 從最後index = n - 1開始累積,i, j 相向而行,

N型就是兩邊小,中間大。那麼我result從最小開始累積,index = 0開始累加;i, j 相向而行,

這題可以跟 Squares of a Sorted Array 一起復習;

class Solution {
    public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
        if(nums == null || nums.length == 0) {
            return new int[0];
        }
        int n = nums.length; 
        int i = 0; int j = n - 1;
        int index = a >= 0 ? n - 1 : 0;
        int[] res = new int[n];
        while(i <= j) {
            if(a >= 0) {
                res[index--] = fx(a, b, c, nums[i]) >= fx(a, b, c, nums[j]) 
                                ? fx(a, b, c, nums[i++]) : fx(a, b, c, nums[j--]);  
            } else {
                res[index++] = (fx(a, b, c, nums[i]) <= fx(a, b, c, nums[j]))
                                ? fx(a, b, c, nums[i++]) : fx(a, b, c, nums[j--]);
            }
        }
        return res;
    }
    
    private int fx(int a, int b, int c, int x) {
        return a * x * x + b * x + c;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章