360. Sort Transformed Array

Given asortedarray of integersnumsand integer valuesa,bandc. Apply a quadratic function of the form f(x) =ax2+bx+cto each elementxin the array.

The returned array must be insorted 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]

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

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[] ans = new int[n];
        int start = 0, end = n - 1;
        int index = a >= 0 ? n - 1 : 0;

        while (start <= end){
            if (a >= 0){
                ans[index--] = calculate(nums[start], a, b, c) >= calculate(nums[end], a, b, c) ? calculate(nums[start++], a, b, c) : calculate(nums[end--], a, b, c);
            }
            else{
                ans[index++] = calculate(nums[start], a, b, c) < calculate(nums[end], a, b, c) ? calculate(nums[start++], a, b, c) : calculate(nums[end--], a, b, c);
            }
        }

        return ans;
    }

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

results for ""

    No results matching ""