4. Sort Transformed Array

Link to the problem

Description

Given a sorted array of integers nums and integer values a, b and c. Apply a quadratic function of the form f(x) = ax2 + bx + c to each element x in the array.

The returned array must be in sorted order.

Expected time complexity: O(n)

Example

Input: [-4, -2, 2, 4], a = 1, b = 3, c = 5, Output: [3, 9, 15, 33]
Input: [-4, -2, 2, 4], a = -1, b = 3, c = 5, Output: [-23, -5, 1, 7]

Idea

First assume a > 0. Since the array is sorted, and quadratic function first decreases, then increases, the transformed array is unimodal (first drop, then rise).
We find the pivot point, and use two pointers to traverse the left part, which is decreasing, and the right part, which is increasing. Merge them as in the merge sort.
If a < 0, first call the function on -a, -b, -c, then negate and reverse the result.

Solution

class Solution {
public:
    vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {
        int n = nums.size();
        if (a < 0) {
            vector<int> rtn = sortTransformedArray(nums, -a, -b, -c);
            for (auto it = rtn.begin(); it != rtn.end(); it++) *it = -(*it);
            reverse(rtn.begin(), rtn.end());
            return rtn;
        }
        for (int i = 0; i < n; i++) {
            nums[i] = a * nums[i] * nums[i] + b * nums[i] + c;
        }
        int right = 0;
        while (right < n && (right == 0 || nums[right] <= nums[right - 1])) {
            right++;
        }
        int left = right - 1;
        vector<int> rtn;
        while (left >= 0 && right < n) {
            if (nums[left] < nums[right]) {
                rtn.push_back(nums[left--]);
            } else {
                rtn.push_back(nums[right++]);
            }
        }
        while (left >= 0) {
            rtn.push_back(nums[left--]);
        }
        while (right < n) {
            rtn.push_back(nums[right++]);
        }
        return rtn;
    }
};

Performance

110 / 110 test cases passed.
Runtime: 9 ms

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,410评论 0 23
  • 今天大雨表现优良,吃了三顿饭,白天没有闹闹的。 早晨妈妈跟大雨说,今天爸爸妈妈要去上班,大雨说为什么呢? 妈妈回答...
    大雨不愁阅读 1,475评论 0 0
  • 当我们使用全局共用数据的时候,可以使用宏、常亮、变量 宏: #define HSCoder @"hello"变量:...
    iChuck阅读 2,915评论 0 0
  • 〈原创〉亲人仙游去,未呈儿孙福。游魂荡千里,如何度思量。思量千百顾,心性命相连。甲子传承续,吾辈当自强。小童知人事...
    籍境观心阅读 2,958评论 0 2
  • 当我置身于华山山顶俯瞰这世间的一切,仿佛世间的所有都如此的渺小,每一次登顶都仿佛在悬崖峭壁,如果没有围栏,便能随时...
    姚五月阅读 2,144评论 0 2