Leetcode Problem:
Summary
- Given an array of integers, replace each element with its rank
- The rank represents how large the element is.
Approach
- The approach used is to first sort the array and then create a map to store the rank of each unique number
- Then, for each number in the original array, find its rank in the map and add it to the result vector.
Complexity
- O(n log n) due to the sorting step, where n is the number of elements in the array.
Solution Code:
class Solution {
public:
vector arrayRankTransform(vector& arr) {
vector arr2 = arr;
sort(arr2.begin(), arr2.end());
unordered_map m;
int rank = 0;
int curNum = -1;
for(int num : arr2){
if(curNum == num){
continue;
}
curNum = num;
rank++;
m[num] = rank;
}
vector ans;
for(int num: arr){
ans.push_back(m[num]);
}
return ans;
}
};
'알고리즘' 카테고리의 다른 글
Divide Players Into Teams of Equal Skill (0) | 2025.02.13 |
---|---|
Make Sum Divisible by P (0) | 2025.02.13 |
Check If Array Pairs Are Divisible by k (0) | 2025.02.13 |
Design a Stack With Increment Operation (0) | 2025.02.13 |
All O`one Data Structure (0) | 2025.02.13 |