LeetCode #360. Sort Transformed Array

本文详细解析了一种在已排序数组上应用二次函数并保持排序的高效算法。通过定义两个指针从两端向中间移动,根据二次函数系数的正负决定结果的填充位置,实现了O(n)的时间复杂度。文章提供了完整的代码实现,并通过两个实例展示了算法的正确性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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]
class Solution {
public:
    vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {
        // ax^2+bx+c=a(x+bx/2a)^2+c-b^2/4a,对称轴是-b/2a
        // 所以当a大于等于0时,定义两个指针往中间移动,依次把结果放入数组末尾
        // a小于0时,定义两个指针往中间移动,依次把结果放入数组开头
        int n=nums.size();
        vector<int> result(n);
        int i=0, j=n-1;
        int count=0;
        while(i<=j)
        {
            int x=a*nums[i]*nums[i]+b*nums[i]+c;
            int y=a*nums[j]*nums[j]+b*nums[j]+c;
            if(a>=0)
            {
                if(x>y) result[n-1-count]=x, i++;
                else result[n-1-count]=y, j--;
            }
            else
            {
                if(x>y)  result[count]=y, j--;
                else result[count]=x, i++;
            }
            count++;
        }
        return result;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值