360 Sort Transformed Array
nums = [-4, -2, 2, 4], a = 1, b = 3, c = 5,
Result: [3, 9, 15, 33]
nums = [-4, -2, 2, 4], a = -1, b = 3, c = 5
Result: [-23, -5, 1, 7]import operator
class Solution:
def sortTransformedArray(self, nums, a, b, c):
"""
:type nums: List[int]
:type a: int
:type b: int
:type c: int
:rtype: List[int]
"""
def quad(x):
return (a * pow(x, 2)) + (b * x) + c
solution = [0] * len(nums)
def iter_forward_or_rev(start, add, cmp):
left = 0
right = len(nums) - 1
while left <= right:
if cmp(quad(nums[left]), quad(nums[right])):
solution[start] = quad(nums[left])
left += 1
else:
solution[start] = quad(nums[right])
right -= 1
start += add
# if a > 0, then left of parabola are largest
# otherwise the ends of parabola are the smallest
if a > 0:
iter_forward_or_rev(len(nums) - 1, -1, operator.gt)
else:
iter_forward_or_rev(0, 1, operator.lt)
return solutionLast updated
