资讯专栏INFORMATION COLUMN

360. Sort Transformed Array

ChristmasBoy / 2402人阅读

摘要:题目链接这是个数学问题,抛物线,我们知道这时候是个凹函数,两遍的值大于中间,所以从两遍开始哪边的大就把结果放到的右边这时候是个凸函数,两遍的值小于中间,所以两遍开始扫哪边的值小就把它放到的左边这时候是单调增的函数,用上面任意一种方法都可以。

360. Sort Transformed Array

题目链接:https://leetcode.com/problems...

这是个数学问题,抛物线,我们知道

a > 0: 这时候是个凹函数,两遍的值大于中间,所以从两遍开始哪边的大就把结果放到result的右边

a < 0: 这时候是个凸函数,两遍的值小于中间,所以两遍开始扫哪边的值小就把它放到result的左边

a == 0: 这时候是单调增的函数,用上面任意一种方法都可以。

public class Solution {
    public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
        int n = nums.length;
        // 2 points
        int i = 0, j = n - 1;
        int k = a > 0 ? n - 1 : 0;
        
        int[] res = new int[n];
        while(i <= j) {
            int left = getF(nums[i], a, b, c);
            int right = getF(nums[j], a, b, c);
            if(a > 0) {
                if(left > right) {
                    res[k--] = left;  i++;
                }
                else {
                    res[k--] = right;  j--;
                }
            }
            else {
                if(left < right) {
                    res[k++] = left;  i++;
                }
                else {
                    res[k++] = right;  j--;
                }
            }
        }
        
        return res;
    }
    
    private int getF(int x, int a, int b, int c) {
        return a * x * x + b * x + c;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69850.html

相关文章

  • 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 ret...

    wua_wua2012 评论0 收藏0

发表评论

0条评论

ChristmasBoy

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<