# 360. Sort Transformed Array

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/sort-transformed-array/

> 内容描述

```
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 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]
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(N)******


小心几个case，就是a或者b可能为0

然后分a大于0和小于0来判断，用抛物线的中线-b/(2*a)来将nums分成两部分，然后就很容易判断出大小了（根据与中线的距离）

```python
class Solution:
    def sortTransformedArray(self, nums: List[int], a: int, b: int, c: int) -> List[int]:
        if a == 0:
            if b > 0:
                return [b * x + c for x in nums]
            elif b == 0:
                return [c] * len(nums)
            else:
                return [b * x + c for x in nums[::-1]]
                
        def quadratic(x):
            return a * x ** 2 + b * x + c
 
        idx = bisect.bisect_left(nums, -b/(2*a))
        if a < 0:
            s1, s2 = nums[:idx], nums[idx:][::-1]
        else:
            s1, s2 = nums[:idx][::-1], nums[idx:]
            
        res, p1, p2 = [], 0, 0
        while p1 < len(s1) and p2 < len(s2):
            tmp1, tmp2 = quadratic(s1[p1]), quadratic(s2[p2])
            if tmp1 <= tmp2:
                res.append(tmp1)
                p1 += 1
            else:
                res.append(tmp2)
                p2 += 1
        for num in s1[p1:]:
            res.append(quadratic(num))
        for num in s2[p2:]:
            res.append(quadratic(num))
        return res
```






































