LeetCode 360. Sort Transformed Array

来源:互联网 发布:图片自动播放软件 编辑:程序博客网 时间:2024/06/03 21:12

Given a sorted array of integers nums and integer values a, b and c. Apply a 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: 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]

思路:
1. 这是一个数学题。计算所有x和对称轴的距离|xb2a,当a<0,则距离越大,|f(x)| 越小;当a>0,距离越大,|f(x)| 越大;当a=0,f(x)=bx+c, b>=0,则f(x) monotonically increasing function, otherwise it’s non-increasing function.
2. 在实际计算中,不用计算|xb2a|,因为不需要绝对值的大小,只需要相对大小即可,所以计算|2ax+b|即可。
3. 如何做到o(n)的复杂度?必须利用输入是sorted array这个条件。先计算所有距离,并根据a符号决定是找出最大值还是最小值的坐标,例如,a>0,则找出距离最小值的坐标,然后把这个值坐标对应的f(x) 计算出来放在输出array最左边,然后用two pointer的方法,从这个最小距离的坐标两侧移动,比较两侧的距离,并把相对小的距离的坐标的f(x) 输出!
4. 还可以继续简化,参考http://www.cnblogs.com/grandyang/p/5595614.html 不用计算并比较距离。可以只利用下面的性质,a>0则抛物线两边比中间大;a>0则抛物线中间比两边大;a=0则根据b来判断是单调递增还是递减。

vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {    int n=nums.size();    vector<int> res(n,0);    for(int i=0;i<n;i++)        nums[i]=a*x*x+b*x+c;    int left=0,right=n-1;    int index=a>=0?n-1:0;    while(left<=right){        if(a>=0){            res[index--]=(nums[left]>=nums[right])?nums[left++]:nums[right--];        }else{            res[index++]=(nums[left]>=nums[right])?nums[right--]:nums[left++];        }    }    return res;}
0 0