Sort Transformed Array
Problem: Sort Transformed Array
The function's graph is a curve, which is able to be sorted easily with two pointers.
Code in Python:
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]
"""
if a == 0:
if b == 0: return [c] * len(nums)
if b > 0: return [b * num + c for num in nums]
if b < 0: return [b * num + c for num in nums[::-1]]
res = []
l, r = 0, len(nums)-1
while l < r:
nl, nr = nums[l], nums[r]
fl, fr = a * nl * nl + b * nl + c, a * nr * nr + b * nr + c
if fl < fr:
if a > 0:
res.append(fr)
r -= 1
else:
res.append(fl)
l += 1
else:
if a > 0:
res.append(fl)
l += 1
else:
res.append(fr)
r -= 1
nl = nums[l]
res.append(a * nl * nl + b * nl + c)
return res if a < 0 else res[::-1]