Sort Transformed Array

Given a sorted array of integers nums and integer values ab 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]

思路:这个方程是个二次方程,也就是个椭圆,那么a > 0的时候,是U型,a < 0 是N型,

也就是如果是U型,那么就是两头大,中间小,那么我result 从最后index = n - 1开始累积,i, j 相向而行,

N型就是两边小,中间大。那么我result从最小开始累积,index = 0开始累加;i, j 相向而行,

这题可以跟 Squares of a Sorted Array 一起复习;

class Solution {
    public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
        if(nums == null || nums.length == 0) {
            return new int[0];
        }
        int n = nums.length; 
        int i = 0; int j = n - 1;
        int index = a >= 0 ? n - 1 : 0;
        int[] res = new int[n];
        while(i <= j) {
            if(a >= 0) {
                res[index--] = fx(a, b, c, nums[i]) >= fx(a, b, c, nums[j]) 
                                ? fx(a, b, c, nums[i++]) : fx(a, b, c, nums[j--]);  
            } else {
                res[index++] = (fx(a, b, c, nums[i]) <= fx(a, b, c, nums[j]))
                                ? fx(a, b, c, nums[i++]) : fx(a, b, c, nums[j--]);
            }
        }
        return res;
    }
    
    private int fx(int a, int b, int c, int x) {
        return a * x * x + b * x + c;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值