360. Sort Transformed Array

一元二次方程。。。仿佛回到了初中。

主要看a的情况来分情况讨论:
=0,一次函数,根据b的正负单调递增递减就行了。
<0,凸状。。从nums[]左右两边开始往中间一边比较一边 从右往左 放;

0,凹状。。从左往右。。

public class Solution {
    public int[] sortTransformedArray(int[] nums, int a, int b, int c) 
    {
        int n = nums.length;
        int[] res = new int[n];
        int i = 0;
        if(a == 0)
        {

            if(b >= 0) while(i < n) res[i] = nums[i++]*b + c;
            else
                while(i < n)
                {
                    res[i] = nums[n-1-i]*b + c;
                    i++;
                }
        }
        else
        {
            int l = 0;
            int r = n-1;
            int M = -b/a;
            
            while(i < n)
            {
                int p = cal(nums[l],a,b,c);
                int q = cal(nums[r],a,b,c);
                
                if(a > 0)
                {
                    if(p > q)
                    {
                        l++;
                        res[n-1-i] = p;
                    }    
                    else
                    {
                        r--;
                        res[n-1-i] = q;
                    }
                }
                else
                {
                    if(p < q)
                    {
                        l++;
                        res[i] = p;
                    }    
                    else
                    {
                        r--;
                        res[i] = q;
                    }
                }
                i++;
            }            
        }
        return res;
        
    }
    
    public int cal(int x, int a, int b, int c)
    {
        return a*x*x + b*x + c;
    }
}
posted @ 2016-10-13 10:52  哇呀呀..生气啦~  阅读(104)  评论(0编辑  收藏  举报