360 Sort Transformed Array
Last updated
Last updated
Given a sorted array of integers nums
and integer values a
,b
and c
. Apply a quadratic 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:
The Idea: The first thing to recognize is that in a parabola, with a != 0
, then ends of the parabola are symmetric about the root, and they are the largest or smallest values of f(x) depending on whether a > 0
or a < 0
. If we begin at the end points of nums
, then we can simply chose the smaller one until the left if a < 0
, on in reverse if a > 0
. Even though there are the cases when a=0 and b>0
ora=0 and b<0
, both these cases can be reduced to following the same logic following when a <= 0
.
Complexity: O(n) time and constant extra space