LeetCode 2377: Sort the Olympic Table

Database

Problem Description

Explanation

To sort the Olympic table, we can use a custom comparator to sort the teams based on their number of gold medals. If two teams have the same number of gold medals, we can compare their number of silver medals. If both gold and silver medals are equal, we can compare their number of bronze medals. If all medals are equal, we can sort based on the team name in lexicographical order.

  1. Create a custom comparator function to compare teams based on their medals.
  2. Sort the teams using the custom comparator.
  3. Return the sorted table.

Time Complexity: O(n log n) - where n is the number of teams Space Complexity: O(1)

Solutions

import java.util.*;

class Solution {
    public String[] sortTable(String[][] table) {
        Arrays.sort(table, new Comparator<String[]>() {
            @Override
            public int compare(String[] a, String[] b) {
                int goldA = Integer.parseInt(a[1]);
                int silverA = Integer.parseInt(a[2]);
                int bronzeA = Integer.parseInt(a[3]);
                
                int goldB = Integer.parseInt(b[1]);
                int silverB = Integer.parseInt(b[2]);
                int bronzeB = Integer.parseInt(b[3]);
                
                if (goldA != goldB) {
                    return Integer.compare(goldB, goldA);
                } else if (silverA != silverB) {
                    return Integer.compare(silverB, silverA);
                } else if (bronzeA != bronzeB) {
                    return Integer.compare(bronzeB, bronzeA);
                } else {
                    return a[0].compareTo(b[0]);
                }
            }
        });
        
        return Arrays.stream(table).map(row -> String.join(" ", row)).toArray(String[]::new);
    }
}

Loading editor...