leetcode360 - Sort Transformed Array - medium

Given a sorted array of integers nums and integer values a, b 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]

 

1.O(nlogn). Trivial solution: 算结果,排序。
2.O(n). 双指针+利用信息。可利用的信息:二元抛物线函数,原来数字已排序。
如果a>0,开口向上,那么两端的数字肯定是最大的,挑出更大的放到结果的右端,一个个遍历重复,即可。
如果a<0,开口向下,那么两端的数字肯定是最小的,挑出更小的放到结果的左端,一个个遍历重复,即可。
如果a==0,直线,从结果的左端放起或者右端放起都可以,合并到上面其中一种。

 

细节:
1.指针所指对象比较时,比的是经过抛物函数计算的结果,而不是原来的数字。

 

实现:

class Solution {
    public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
        int[] ans = new int[nums.length];
        int i = 0, j = nums.length - 1, k = 0;
        while (i <= j) {
            int calI = cal(nums[i], a, b, c);
            int calJ = cal(nums[j], a, b, c);
            if (a > 0) {
                if (calI > calJ) {
                    ans[ans.length - 1 - k++] = calI;
                    i++;
                } else {
                    ans[ans.length - 1 - k++] = calJ;
                    j--;
                }
            } else {
                if (calI < calJ) {
                    ans[k++] = calI;
                    i++;
                } else {
                    ans[k++] = calJ;
                    j--;
                }
            }
        }
        return ans;
    }
    
    private int cal(int x, int a, int b, int c) {
        return a * x * x + b * x + c;
    }
}

 

posted @ 2018-10-03 12:47  jasminemzy  阅读(138)  评论(0编辑  收藏  举报