Posted on

Description

Submission

class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int n = nums.size();
        auto it = lower_bound(nums.begin(), nums.end(), 0);

        int left, right;
        if(it == nums.end()) {
            right = n;
            left = n - 1;
        } else {
            right = it - nums.begin();
            left = right - 1;
        }
        vector<int> rets;
        while(right < n || left >= 0) {
            if(right >= n) {
                rets.push_back(nums[left] * nums[left]);
                --left;
            } else if(left < 0) {
                rets.push_back(nums[right] * nums[right]);
                ++right;
            } else {
                int l = nums[left] * nums[left];
                int r = nums[right] * nums[right];
                if(l < r) {
                    rets.push_back(l);
                    --left;
                } else {
                    rets.push_back(r);
                    ++right;
                }
            }
        }

        return rets;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *