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]

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

Solution

public class Solution {
 public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
        if (nums == null || nums.length == 0) return new int[0];

        int[] result = new int[nums.length];
        if (a > 0) {
            int start = 0;
            int end = nums.length - 1;
            int index = nums.length - 1;

            while (start <= end) {
                int startX = getValue(a, b, c, nums[start]);
                int endX = getValue(a, b, c, nums[end]);

                if (startX >= endX) {
                    result[index] = startX;
                    index--;
                    start++;
                } else {
                    result[index] = endX;
                    index--;
                    end--;
                }
            }
        } else if (a < 0) {
            int start = 0;
            int end = nums.length - 1;
            int index = 0;

            while (start <= end) {
                int startX = getValue(a, b, c, nums[start]);
                int endX = getValue(a, b, c, nums[end]);

                if (startX >= endX) {
                    result[index] = endX;
                    index++;
                    end--;
                } else {
                    result[index] = startX;
                    index++;
                    start++;
                }
            }
        } else {
            if (b > 0) {

                for (int i = 0; i < nums.length; i++) {
                    result[i] = getValue(a, b, c, nums[i]);
                }

            } else if (b < 0) {
                for (int i = 0; i < nums.length; i++) {
                    result[nums.length - i - 1] = getValue(a, b, c, nums[i]);
                }
            } else {
                for(int i = 0; i < nums.length; i ++) {
                    result[i] = c;
                }

            }
        }

        return result;
    }

    private int getValue(int a, int b, int c, int x) {
        return (int) (a * Math.pow(x, 2) + b * x + c);
    }
}

results matching ""

    No results matching ""