1ms JAVA solution


  • 0
    E
    public static int[] sortTransformedArray(int[] nums, int a, int b, int c) {
        int[] res = new int [nums.length];
        if (a == 0) {
            if (b >= 0) {
                res = nums;
            }
            else {
                for (int i = 0; i < nums.length; i++) {
                    res[nums.length - 1 - i] = nums[i];
                }
            }
        }
    
        float pivot = 0 - (float)b / (2 * a);
        int left = 0;
        int right = 0;
        int index = 0;
    
        if (a > 0) {
            left = binarySearch(nums, pivot);
            right = left + 1;
            while (left >= 0 && right < nums.length) {
                res[index++] = (pivot - nums[left]) > (nums[right] - pivot) ? nums[right++] : nums[left--];
            }
            while (left >= 0) {
                res[index++] = nums[left--];
            }
            while (right < nums.length) {
                res[index++] = nums[right++];
            }
        }
        else if (a < 0) {
            left = 0;
            right = nums.length - 1;
            while (nums[left] <= pivot && nums[right] >= pivot) {
                res[index++] = (pivot - nums[left]) > (nums[right] - pivot) ? nums[left++] : nums[right--];
            }
            while (left < nums.length && nums[left] < pivot) {
                res[index++] = nums[left++];
            }
            while (right >= 0 && nums[right] > pivot) {
                res[index++] = nums[right--];
            }
        }
    
        for (int i = 0; i < res.length; i++) {
            res[i] = res[i] * res[i] * a + b * res[i] + c;
        }
        return res;
    }
    
    public static int binarySearch(int[] array, float target) {
        int left = 0;
        int right = array.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (array[mid] == target)
                return mid;
            if (array[mid] < target) {
                left = mid + 1;
            }
            else {
                right = mid - 1;
            }
        }
        return left - 1;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.