360. Sort Transformed Array
Given asortedarray of integersnumsand integer valuesa,bandc. Apply a quadratic function of the form f(x) =ax2+bx+cto each elementxin the array.
The returned array must be insorted order.
Expected time complexity:O(n)
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]Thoughts:
Identify & utilize the convexity & concavity of the quadratic function based on a value
Use to pointers to select two candidate nums[left] and nums[right]
Code O(n)
class Solution(object):
def sortTransformedArray(self, nums, a, b, c):
"""
:type nums: List[int]
:type a: int
:type b: int
:type c: int
:rtype: List[int]
"""
def qua(x, a, b, c):
return a * x ** 2 + b * x + c
n = len(nums)
left , right = 0, n - 1
ans = []
while left<= right:
left_val = qua(nums[left], a ,b ,c)
right_val = qua(nums[right], a ,b ,c)
if a >= 0: # a == 0: put larger at the end or smaller in the front both would be ok
if left_val <= right_val: # a > 0 find larger value garanteed larger than any number in the list; put at the end
ans =[right_val] + ans
right -= 1
else:
ans = [left_val] + ans
left += 1
else:
if left_val <= right_val: # a > 0 find smaller value garanteed smaller than any number in the list; put in the front
ans.append(left_val)
left += 1
else:
ans.append(right_val)
right -= 1
return ansJava
Last updated
Was this helpful?