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.
Example 1:
Input: arr = 40,10,20,30
Output: 4,1,2,3
Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.
Example 2:
Input: arr = 100,100,100
Output: 1,1,1
Explanation: Same elements share the same rank.
Example 3:
Input: arr = 37,12,28,9,100,56,80,5,12
Output: 5,3,4,2,8,6,7,1,3
Constraints:
- 0 < = a r r . l e n g t h < = 10 5 0 <= arr.length <= 10^5 0<=arr.length<=105
- − 10 9 < = a r r i < = 10 9 -10^9 <= arri <= 10^9 −109<=arri<=109
From: LeetCode
Link: 1331. Rank Transform of an Array
Solution:
Ideas:
The sorted unique values determine the ranks. For example, 40,10,20,30 becomes 10,20,30,40, so their ranks are 1,2,3,4.
Code:
c
#include <stdlib.h>
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
static int compareInts(const void* a, const void* b) {
int x = *(const int*)a;
int y = *(const int*)b;
if (x < y) return -1;
if (x > y) return 1;
return 0;
}
static int findRank(int* values, int size, int target) {
int left = 0;
int right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (values[mid] == target) {
return mid + 1;
} else if (values[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int* arrayRankTransform(int* arr, int arrSize, int* returnSize) {
*returnSize = arrSize;
if (arrSize == 0) {
return NULL;
}
int* sorted = malloc(arrSize * sizeof(int));
int* answer = malloc(arrSize * sizeof(int));
for (int i = 0; i < arrSize; i++) {
sorted[i] = arr[i];
}
qsort(sorted, arrSize, sizeof(int), compareInts);
/* Remove duplicate values in place. */
int uniqueCount = 0;
for (int i = 0; i < arrSize; i++) {
if (i == 0 || sorted[i] != sorted[i - 1]) {
sorted[uniqueCount++] = sorted[i];
}
}
for (int i = 0; i < arrSize; i++) {
answer[i] = findRank(sorted, uniqueCount, arr[i]);
}
free(sorted);
return answer;
}