1. 程式人生 > >leetcode360 - Sort Transformed Array - medium

leetcode360 - Sort Transformed Array - medium

example ive must 重復 class sorted 實現 對象比較 log

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

leetcode360 - Sort Transformed Array - medium