Relative Ranks - Java Solution using TreeMap


  • 0
    D
    public class Solution {
        public String[] findRelativeRanks(int[] nums) {
            String[] ranks = new String[nums.length];
            int i = 0;
            
            TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
            for(i = 0; i <  nums.length; i++ )
                map.put(nums[i], i);
            
            Set set = map.entrySet();
            Iterator it = set.iterator();
            
            int rank = nums.length;
            int index;
            
            while(it.hasNext()) {
                Map.Entry cur = (Map.Entry)it.next();
                index = (int)cur.getValue();
                if(rank == 1) 
                        ranks[index] = "Gold Medal";
                else if( rank == 2)
                        ranks[index] = "Silver Medal";
                else if( rank == 3)
                        ranks[index] = "Bronze Medal";
                else
                        ranks[index] = rank + "";
                rank--;
            }
            return ranks;
        }
    }
    

Log in to reply
 

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