Java solution with some other classes used


  • 0
    R
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    import javafx.util.Pair;
    
    public class Solution {
        
        private static final String[] MEDALS = new String[]{"Gold Medal", "Silver Medal", "Bronze Medal"};
        
        public String[] findRelativeRanks(int[] nums) {
            if (0 == nums.length) {
                return null;
            }
            List<Pair<Integer, Integer>> list = new ArrayList<>();
            String[] result = new String[nums.length];
            for (int i = 0; i < nums.length; i++) {
                list.add(new Pair<>(i, nums[i]));
            }
            //Sort by score, highest one will be put in thehead
            Collections.sort(list, (Pair<Integer, Integer> a, Pair<Integer, Integer> b) -> b.getValue() - a.getValue());
            for (int i = 0; i < list.size(); i++) {
                //Generate result by its original order
                result[list.get(i).getKey()] = Integer.toString(i + 1);
            }
            //In case where length is less than 3
            for (int i = 0; i < Math.min(3, nums.length); i++) {
                //Special names
                result[list.get(i).getKey()] = MEDALS[i];
            }
    
            return result;
        }
    }
    

Log in to reply
 

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