Concise C++ Solution 8ms


  • 0
    S
    class Solution {
    public:
        vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {
            if (nums.empty()) return vector<int>();
            
            vector<int> res(nums.size(), 0);
            if (a!=0) {
                double mid = -(double)b/(2*(double)a);
                int head = 0, tail = nums.size()-1, idx = 0, x = 0;
                while (head<=tail) {
                    if (abs((double)nums[head]-mid)<=
                        abs((double)nums[tail]-mid)) {
                        x = nums[tail]; --tail;
                    } else {
                        x = nums[head]; ++head;
                    }
                    res[idx++] = a*x*x+b*x+c;
                }
            } else {
                for (int i=0; i<nums.size(); ++i) res[i] = b*nums[i]+c;
            }
            
            if (a>0 || (a==0 && b<0)) reverse(res.begin(), res.end());
            return res;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.