Leetcode 1331. Rank Transform of an Array
Given an array of integers arr
, replace each element with its rank. The rank represents how small the element is. The rank should be a number starting from 1 and representing the relative size of the element compared to the other elements in the array.
The rank should be calculated such that:
Example:
Input: arr = [40, 10, 20, 30]
Output: [4, 1, 2, 3]
Input: arr = [100, 100, 100]
Output: [1, 1, 1]
Input: arr = [37, 12, 28, 9, 100, 56, 80, 5, 12]
Output: [5, 3, 4, 2, 8, 6, 7, 1, 3]
To transform the array into ranks, the steps are:
#include <vector>
#include <unordered_map>
#include <algorithm>
std::vector<int> arrayRankTransform(std::vector<int>& arr) {
if (arr.empty()) {
return {};
}
std::vector<int> sortedArr = arr;
std::sort(sortedArr.begin(), sortedArr.end());
std::unordered_map<int, int> rankMap;
int rank = 1;
for (const int& num : sortedArr) {
if (rankMap.find(num) == rankMap.end()) {
rankMap[num] = rank++;
}
}
std::vector<int> result;
result.reserve(arr.size());
for (const int& num : arr) {
result.push_back(rankMap[num]);
}
return result;
}
O(n log n)
where n
is the number of elements in the array.O(n)
since we iterate through the sorted array and create map entries.O(n)
to iterate through the original array and construct the result.Thus, the overall time complexity is O(n log n)
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?