Sort Transformed Array in C++

C++Server Side ProgrammingProgramming

Suppose we have a sorted array of integer nums and integer values a, b and c. We have to apply a quadratic function of the form f(x) = ax^2 + bx + c to each element x in the array. And the final array must be in sorted order.

So, if the input is like nums = [-4,-2,2,4], a = 1, b = 3, c = 5, then the output will be [3,9,15,33]

To solve this, we will follow these steps −

  • Define function f(), that takes x, a, b, c −

  • return ax^2 + bx + c

  • From the main method do the following −

  • n := size of nums

  • start := 0, end := n - 1

  • Define an array ret of size n

  • if a >= 0, then −

    • for initialize i := n - 1, when i >= 0, update (decrease i by 1), do −

      • x := f(nums[start], a, b, c)

      • y := f(nums[end], a, b, c)

      • if x > y, then −

        • (increase start by 1)

        • ret[i] := x

      • Otherwise

        • ret[i] := y

        • (decrease end by 1)

  • Otherwise

    • for initialize i := 0, when i < n, update (increase i by 1), do −

      • x := f(nums[start], a, b, c)

      • y := f(nums[end], a, b, c)

      • if x < y, then −

        • (increase start by 1)

        • ret[i] := x

      • Otherwise

        • ret[i] := y

        • (decrease end by 1)

  • return ret

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto< v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   int f(int x, int a, int b, int c){
      return a * x * x + b * x + c;
   }
   vector<int< sortTransformedArray(vector<int<& nums, int a, int b, int c) {
      int n = nums.size();
      int start = 0;
      int end = n - 1;
      vector<int< ret(n);
      if (a >= 0) {
         for (int i = n - 1; i >= 0; i--) {
            int x = f(nums[start], a, b, c);
            int y = f(nums[end], a, b, c);
            if (x > y) {
               start++;
               ret[i] = x;
            }
            else {
               ret[i] = y;
               end--;
            }
         }
      }
      else {
         for (int i = 0; i < n; i++) {
            int x = f(nums[start], a, b, c);
            int y = f(nums[end], a, b, c);
            if (x < y) {
               start++;
               ret[i] = x;
            }
            else {
               ret[i] = y;
               end--;
            }
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<int< v = {-4,-2,2,4};
   print_vector(ob.sortTransformedArray(v, 1, 3, 5));
}

Input

{-4,-2,2,4}, 1, 3, 5

Output

[3, 9, 15, 33, ]
raja
Published on 19-Nov-2020 14:04:00
Advertisements