Sponsored
Sponsored
This approach involves sorting the array to determine the rank of each element. After sorting, unique elements are mapped to their ranks.
Time Complexity: O(N log N) due to sorting.
Space Complexity: O(N) for storing the sorted array and rank map.
1#include <stdio.h>
2#include <stdlib.h>
3
4int cmpfunc (const void * a, const void * b) {
5 return ( *(int*)a - *(int*)b );
6}
7
8int* arrayRankTransform(int* arr, int arrSize, int* returnSize) {
9 *returnSize = arrSize;
10 if (arrSize == 0) return NULL;
11
12 int* sorted = (int*)malloc(arrSize * sizeof(int));
13 for (int i = 0; i < arrSize; i++) sorted[i] = arr[i];
14 qsort(sorted, arrSize, sizeof(int), cmpfunc);
15
16 int* rankMap = (int*)malloc(arrSize * sizeof(int));
17 int rank = 1;
18 rankMap[0] = sorted[0];
19 int rankArr[1] = {rank};
20
21 for (int i = 1; i < arrSize; i++) {
22 if (sorted[i] != sorted[i - 1]) {
23 rank++;
24 }
25 rankArr[rank] = sorted[i];
26 }
27
28 int* result = (int*)malloc(arrSize * sizeof(int));
29 for (int i = 0; i < arrSize; i++) {
30 for (int j = 0; j < rank; j++) {
31 if (arr[i] == rankMap[j]) {
32 result[i] = j + 1;
33 break;
34 }
35 }
36 }
37
38 free(sorted);
39 free(rankMap);
40 return result;
41}
The C solution involves sorting the array and creating a map of ranks. Sorted unique elements are assigned ranks incrementally. The original elements are then mapped to their ranks using this mapping.
Coordinate compression is a method to map large ranges of numbers to smaller ranges, maintaining their relative order. This approach uses this idea to assign ranks.
Time Complexity: O(N log N) due to sorting and binary search operations.
Space Complexity: O(N) for rank maps.
1#include <vector>
2#include <unordered_map>
3#include <algorithm>
4using namespace std;
5
vector<int> arrayRankTransform(vector<int>& arr) {
vector<int> sorted = arr;
sort(sorted.begin(), sorted.end());
unordered_map<int, int> rankMap;
int rank = 1;
for (int num : sorted) {
if (!rankMap.count(num)) {
rankMap[num] = rank++;
}
}
vector<int> result(arr.size());
transform(arr.begin(), arr.end(), result.begin(), [&rankMap](int num) { return rankMap[num]; });
return result;
}
This C++ approach applies coordinate compression using data transformation, facilitated by sorting and a mapping scheme. The transformation process ensures ranks are accurately assigned.