Rank Transform of an Array

Given an array of integers arr, replace each element with its rank.

The rank represents how large the element is. The rank has the following rules:

1. Rank is an integer starting from 1.

2. The larger the element, the larger the rank. If two elements are equal, their rank must be the same.

3. The rank should be as small as possible.

Example :

Input: arr = [40,10,20,30]
Output: [4,1,2,3]
Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

vector<intarrayRankTransform(vector<int&arr)
{
    vector<int> newArray;
    for (int i = 0; i < arr.size(); i++)
        newArray.push_back(arr[i]);

    sort(newArray.begin(), newArray.end());

    map<intint> rank;
    int rankCount = 1;

    for (int i = 0; i < arr.size(); i++)
    {
        if (rank[newArray[i]] == 0)
        {
            rank[newArray[i]] = rankCount++;
        }
    }
    for (int i = 0; i < arr.size(); i++)
    {
        arr[i] = rank[arr[i]];
    }
    return arr;
}
int main()
{
    vector<int> arr = {40102030};

    vector<int> rank = arrayRankTransform(arr);

    cout << "[";
    for (int i = 0; i < rank.size(); i++)
    {
        cout << arr[i];
        if (i != rank.size() - 1)
            cout << ",";
    }
    cout << "]";
    return 0;
}


No comments:

Post a Comment