LeetCode 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)=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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值