0360. Sort Transformed Array
https://leetcode.com/problems/sort-transformed-array
Description
Given a sorted integer array nums
and three integers a
, b
and c
, apply a quadratic function of the form f(x) = ax2 + bx + c
to each element nums[i]
in the array, and return the array in a sorted order.
Example 1:
**Input:** nums = [-4,-2,2,4], a = 1, b = 3, c = 5
**Output:** [3,9,15,33]
Example 2:
**Input:** nums = [-4,-2,2,4], a = -1, b = 3, c = 5
**Output:** [-23,-5,1,7]
Constraints:
1 <= nums.length <= 200
-100 <= nums[i], a, b, c <= 100
nums
is sorted in ascending order.
Follow up: Could you solve it in O(n)
time?
ac
class Solution {
public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
// edge cases
if (nums == null || nums.length == 0) return new int[0];
int[] res = new int[nums.length];
// 2 pointers
int l = 0, r = res.length - 1;
if (a < 0) {
int i = l;
while (l <= r) {
int left = a * nums[l] * nums[l] + b * nums[l] + c;
int right = a * nums[r] * nums[r] + b * nums[r] + c;
if (left < right) {
res[i++] = left;
l++;
} else {
res[i++] = right;
r--;
}
}
} else {
int i = r;
while (l <= r) {
int left = a * nums[l] * nums[l] + b * nums[l] + c;
int right = a * nums[r] * nums[r] + b * nums[r] + c;
if (left > right) {
res[i--] = left;
l++;
} else {
res[i--] = right;
r--;
}
}
}
return res;
}
}
/*
upward, downward
*/
Last updated
Was this helpful?