[LeetCode] Rank Transform of an Array

1331. 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:

  • Rank is an integer starting from 1.
  • The larger the element, the larger the rank. If two elements are equal, their rank must be the same.
  • Rank should be as small as possible.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<int> arrayRankTransform(vector<int>& arr) {
vector<int> S = arr;
sort(begin(S), end(S));
unordered_map<int,int> mp;
for(int i = 0, ord = 1; i < S.size(); i++) {
if(!i or S[i] != S[i-1]) {
mp[S[i]] = ord++;
}
}
for(auto& x : arr) x = mp[x];
return arr;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/10/02/PS/LeetCode/rank-transform-of-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.