Write a program to replace each element of the array by its rank in the array.
Rank: The rank of an element is defined as the distance with the first element of the array when the array is sorted in increasing order.
If two or more are the same then their rank is also the same.
Example:
Input: arr[]={4,10,5,3,6}
Output: 2 5 3 1 4
Approach
C++
#include <bits/stdc++.h>using namespace std;void rankArray(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<int, int> 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]];}}int main(){vector<int> arr = {4, 10, 5, 3, 6};rankArray(arr);for (int i = 0; i < arr.size(); i++){cout << arr[i] << " ";}return 0;}
No comments:
Post a Comment