yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #360. Sort Transformed Array #274

Open yokostan opened 5 years ago

yokostan commented 5 years ago
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[] res = new int[n];

        if (a == 0) {
            for (int i = 0; i < n; i++) {
                int x = b >= 0 ? nums[i] : nums[n - i - 1];
                res[i] = b * x + c;
            }
            return res;
        }

        double axis = (double)- b / (2*a);
        int[] distSorted = new int[n];
        int lo = 0, hi = n - 1, end = n - 1;
        while (lo <= hi) {
            double d1 = axis - nums[lo], d2 = nums[hi] - axis;
            if (d1 > d2) {
                distSorted[end--] = nums[lo++];
            }
            else {
                distSorted[end--] = nums[hi--];
            }
        }

        for (int i = 0; i < n; i++) {
            int x = a > 0 ? distSorted[i] : distSorted[n - 1 - i];
            res[i] = a*x*x + b*x + c;
        }

        return res;
    }
}