1331. Rank Transform of an Array #654
Answered
by
kovatz
mah-shamim
asked this question in
Q&A
-
Topics: Given an array of integers The rank represents how large the element is. The rank has the following rules:
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Answered by
kovatz
Oct 2, 2024
Replies: 1 comment 2 replies
-
We can break it down into the following steps:
Let's implement this solution in PHP: 1331. Rank Transform of an Array <?php
/**
* @param Integer[] $arr
* @return Integer[]
*/
function arrayRankTransform($arr) {
// If the array is empty, return an empty array
if (empty($arr)) {
return [];
}
// Step 1: Copy the original array and sort it
$sorted = $arr;
sort($sorted);
// Step 2: Use a hash map to store the rank of each element
$rank = array();
$current_rank = 1;
foreach ($sorted as $value) {
// Assign rank only if the element has not been assigned a rank yet
if (!isset($rank[$value])) {
$rank[$value] = $current_rank;
$current_rank++;
}
}
// Step 3: Replace elements in the original array with their ranks
$result = array();
foreach ($arr as $value) {
$result[] = $rank[$value];
}
return $result;
}
// Example usage:
$arr1 = [40, 10, 20, 30];
print_r(arrayRankTransform($arr1)); // Output: [4, 1, 2, 3]
$arr2 = [100, 100, 100];
print_r(arrayRankTransform($arr2)); // Output: [1, 1, 1]
$arr3 = [37, 12, 28, 9, 100, 56, 80, 5, 12];
print_r(arrayRankTransform($arr3)); // Output: [5, 3, 4, 2, 8, 6, 7, 1, 3]
?> Explanation:
Time Complexity:
This solution efficiently handles large arrays while maintaining simplicity. |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
mah-shamim
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We can break it down into the following steps:
Let's implement this solution in PHP: 1331. Rank Transform of an Array