Sponsored
Sponsored
This approach involves sorting the scores in descending order, then iteratively assigning ranks to each score while handling ties appropriately. This can be efficiently achieved using a sorting algorithm followed by a traversal to assign ranks. By maintaining an index while sorting, we can assign ranks directly to the original scores.
Time Complexity: O(n log n) due to the sorting operation.
Space Complexity: O(1), only a fixed amount of additional memory is used for sorting.
1
Solve with full IDE support and test cases
This Java implementation stores scores in an `ArrayList` and sorts them using a comparator for descending order. The method iterates over the sorted list to print each score along with its corresponding rank, managing ties as described.
This approach uses a bucket sort strategy, particularly efficient when scores have a limited range of decimal places. This reduces the complexity substantially in scenarios where HTTP (High Throughput Processing) is required. Counting occurrences of each score allows direct assignment of ranks in descending order of scores efficiently.
Time Complexity: O(n + k), where n is the number of scores, and k is the number of buckets (constant in this case).
Space Complexity: O(k), which is fixed and depends on BUCKET_COUNT.
1#include <stdio.h>
2#define MAX_SCORE 100.00
3#define MIN_SCORE 0.00
4#define BUCKET_SIZE 0.01
5#define BUCKET_COUNT ((int)((MAX_SCORE - MIN_SCORE) / BUCKET_SIZE + 1))
6
7void rankScores(double scores[], int n) {
8 int buckets[BUCKET_COUNT] = {0};
9
10 for (int i = 0; i < n; i++) {
11 int index = (int)((scores[i] - MIN_SCORE) / BUCKET_SIZE);
12 buckets[index]++;
13 }
14
15 int rank = 0;
16 for (int i = BUCKET_COUNT - 1; i >= 0; i--) {
17 if (buckets[i] > 0) {
18 rank += 1;
19 printf("Score: %.2f, Rank: %d\n", MIN_SCORE + i * BUCKET_SIZE, rank);
20 rank += (buckets[i] - 1);
21 }
22 }
23}
24
25int main() {
26 double scores[] = {3.50, 3.65, 4.00, 3.85, 4.00, 3.65};
27 int n = sizeof(scores) / sizeof(scores[0]);
28 rankScores(scores, n);
29 return 0;
30}
The C bucket sort implementation converts each score based on its proximity to MIN_SCORE using a defined bucket size. Each score increments its corresponding bucket to count occurrences. The ranks are assigned by iteratively checking non-empty buckets from highest to lowest.