【LeetCode刷题-双指针】--360.有序转化数组

360.有序转化数组

【LeetCode刷题-双指针】--360.有序转化数组_第1张图片

方法:双指针

从两头计算,保存两端较小的值,高中抛物线知识,a>0,向上的抛物线,两端大中间小,从后往前存储计算结果;a<0,向下的抛物线,两端小中间大,从前往后存储计算结果

class Solution {
    public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
        int n = nums.length,s = 0;
        int index = n-1;
        int[] ans = new int[n];
        int start = 0,end = n -1;
        while(start <= end){
            if(a>=0){
                ans[index--] = func(nums[start],a,b,c) >= func(nums[end],a,b,c)?func(nums[start++],a,b,c):func(nums[end--],a,b,c);
            }else{
                ans[s++] = func(nums[start],a,b,c) > func(nums[end],a,b,c)?func(nums[end--],a,b,c):func(nums[start++],a,b,c);
            }
        }
        return ans;


    }
    private int func(int x,int a,int b,int c){
        return a*x*x + b*x + c;
    }
}

你可能感兴趣的:(LeetCode,leetcode,算法)