LeetCode 360. Sort Transformed Array

LC address: https://leetcode.com/problems/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]

Analysis:

基本就是一道应用数学题,没什么意思,甚至说比较无聊,仔细一点就可以了。

Solution:

快睡着了,写得不好,也懒得注释了,随便看看吧。

public class Solution {
    public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
        int[] result = new int[nums.length];
        double pivot = (a != 0) ? (- b + 0.0) / (2 * a) :  nums[0];
        boolean isLargest = a < 0 || (a == 0 && b < 0);
        int right = 0;
        double diff = Integer.MAX_VALUE;
        for (int i = 0; i  Math.abs(nums[i] - pivot)) {
                diff = Math.abs(nums[i] - pivot);
                right = i;
            }
        }
        int left = right - 1;
        int i = 0;
        while (right = 0) {
            int j = isLargest ? (nums.length - 1 - i) : i;
            if (Math.abs(nums[left] - pivot) < Math.abs(nums[right] - pivot)) {
                result[j] = calculate(nums[left], a, b, c);
                left -= 1;
            } else {
                result[j] = calculate(nums[right], a, b, c);
                right += 1;
            }
            i += 1;
        }
        while (i < nums.length) {
            int j = isLargest ? (nums.length - 1 - i) : i;
            result[j] = (left < 0) ? calculate(nums[right], a, b, c) : calculate(nums[left], a, b, c);
            left -= 1;
            right += 1;
            i += 1;
        }
        return result;
    }

    private int calculate(int n, int a, int b, int c) {
        return a * n * n + b * n + c;
    }
}

Solution code can also be found here: https://github.com/all4win/LeetCode.git

One comment

Leave a comment