[抄题]:
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]
[暴力解法]:
时间分析:
空间分析:
[优化后]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
不知道和指针对撞有啥关系:谁的平方比较大(绝对值大)数组就先加谁
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[一句话思路]:
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- int startIndex = (a >= 0) ? nums.length - 1 : 0; 变量声明必须写在最前面,不能写在里面
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
不知道和指针对撞有啥关系:谁的平方比较大(绝对值大)数组就先加谁
[复杂度]:Time complexity: O(n) Space complexity: O(n)
[算法思想:迭代/递归/分治/贪心]:
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
[是否头一次写此类driver funcion的代码] :
[潜台词] :
class Solution { public int[] sortTransformedArray(int[] nums, int a, int b, int c) { //initialization: int[] nums, i & j int[] sorted = new int[nums.length]; Arrays.sort(nums); //corner case if (nums == null || nums.length == 0) return sorted; int i = 0; int j = nums.length - 1; //initialization: startIndex, depend on a //must be in one-line int startIndex = (a >= 0) ? nums.length - 1 : 0; //while i <= j, add to result according to a while (i <= j) { if (a >= 0) { sorted[startIndex--] = quad(a, b, c, nums[i]) > quad(a, b, c, nums[j]) ? quad(a, b, c, nums[i++]) : quad(a, b, c, nums[j--]); }else { sorted[startIndex++] = quad(a, b, c, nums[i]) > quad(a, b, c, nums[j]) ? quad(a, b, c, nums[j--]) : quad(a, b, c, nums[i++]); } } //return return sorted; } public int quad(int a, int b, int c, int x) { return a * x * x + b * x + c; } }