Easy Readable Java solution, Sorting


  • 0
    public static String[] findRelativeRanks(int[] nums) {
        String[] ranks = new String[nums.length];
        ArrayList<ScoreRank> scoreRanks = new ArrayList<>();
        int index = 0;
        for (int num : nums) {
            scoreRanks.add(new ScoreRank(index, num));
            index++;
        }
        Collections.sort(scoreRanks, (o1, o2) -> o2.score - o1.score);
        String[] medals = {"Gold Medal", "Silver Medal", "Bronze Medal"};
        for (int i = 0; i < nums.length && i < 3; i++) {
            ranks[scoreRanks.get(i).index] = medals[i];
        }
        for (int i = 3; i < scoreRanks.size(); i++) {
            ScoreRank sr = scoreRanks.get(i);
            ranks[sr.index] = String.valueOf(i+1);
            index++;
        }
        return ranks;
    }
    
    private static class ScoreRank {
        int index;
        int score;
    
        public ScoreRank(int index, int score) {
            this.index = index;
            this.score = score;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.