506. Relative Ranks #156
-
Topics: You are given an integer array The athletes are placed based on their scores, where the
Return an array Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can follow these steps:
Let's implement this solution in PHP: 506. Relative Ranks <?php
function findRelativeRanks($score) {
$n = count($score);
$ranked = $score;
// Step 1: Sort the scores in descending order while keeping track of original indices
arsort($ranked);
// Step 2: Assign ranks
$ranks = array();
$index = 0;
foreach ($ranked as $originalIndex => $value) {
$index++;
if ($index == 1) {
$ranks[$originalIndex] = "Gold Medal";
} elseif ($index == 2) {
$ranks[$originalIndex] = "Silver Medal";
} elseif ($index == 3) {
$ranks[$originalIndex] = "Bronze Medal";
} else {
$ranks[$originalIndex] = (string)$index;
}
}
// Step 3: Prepare the result array based on the original scores' indices
$result = array();
for ($i = 0; $i < $n; $i++) {
$result[$i] = $ranks[$i];
}
return $result;
}
// Test cases
print_r(findRelativeRanks([5, 4, 3, 2, 1])); // Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"]
print_r(findRelativeRanks([10, 3, 8, 9, 4])); // Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"]
?> Explanation:
Test Cases:
This solution efficiently handles the problem within the constraints provided. |
Beta Was this translation helpful? Give feedback.
We can follow these steps:
Let's implement this solution in PHP: 506. Relative Ranks