# Question

Formatted question description: https://leetcode.ca/all/360.html

 360	Sort Transformed Array

Given a sorted array of integers nums and integer values a, b and c.
Apply a function of the form f(x) = ax^2 + bx + c to each element x in the array.

The returned array must be in sorted order.

Expected time complexity: O(n)

Example:

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]


# Algorithm

This question uses a lot of high school mathematical knowledge about parabola. We know that for an equation f(x) = ax2 + bx + c,

• If a>0, the opening of the parabola is upward, and the value at both ends is greater than the middle,
• If a<0, the opening of the parabola faces downward, and the values ​​at both ends are smaller than the middle.
• When a=0, it is a straight line method, which is monotonically increasing or decreasing.

Then we can use this property to solve the problem. The title shows that the given array nums is ordered. If it is not ordered, I think it is difficult to have an O(n) solution. Because the input array is in order, we can discuss the situation according to a:

• When a>0, it means that the value at both ends is greater than the value in the middle. At this time, we fill in from the result after res, and use two pointers to point to the beginning and end of the nums array respectively. The two numbers pointed to are parabolic At the end of the number, the larger of them is stored at the end of res, and then the pointer is moved to the middle, and the comparison process is repeated until the res is filled.

• When a<0, it means that the value at both ends is smaller than the middle, then we fill in from the front of res and use two pointers to point to the beginning and the end of the nums array respectively. The two numbers pointed to are the numbers at both ends of the parabola. The smaller number among them is first stored at the beginning of res, and then the pointer moves to the middle, and the comparison process is repeated until all res is filled.

• When a=0, the function is monotonically increasing or decreasing, then fill in from front to back and fill in from back to front can be done, we can combine this situation with a>0

Java