Java TreeMap method

  • 0

    The key points for this problem are:

    1. sort the scores by descending order
    2. find the mapping between the scores and its original index

    To achieve the 2 points simultaneously, I used TreeMap which is a red-black tree and gives sorting information.

    for TreeMap, both key and value are objects and in my implementation the value in each map entry is index information, however I have to convert Integer to int for indexing. I used int ind = Integer.parseInt(me.getValue().toString()); to solve this. I don't know if there is any other better way to do that.

    I think the time complexity is O(nlogn) for adding/retrieving one tree node is O(logn).

    public String[] findRelativeRanks(int[] nums) {
            TreeMap tm = new TreeMap();
            String [] res = new String[nums.length];
            for(int i = 0; i<nums.length; i++)
                tm.put(-nums[i], i);
            Set set = tm.entrySet();
            Iterator it = set.iterator();
            int count = 1;
            while(it.hasNext()) {
                Map.Entry me = (Map.Entry);
                int ind = Integer.parseInt(me.getValue().toString());
                if(count == 1 )
                     res[ind] = "Gold Medal";
                else if(count == 2)
                    res[ind] = "Silver Medal";
                else if(count == 3)
                    res[ind] = "Bronze Medal";
                    res[ind] = Integer.toString(count);        
                    count ++;
                //  System.out.print(me.getKey() + ": ");
                // System.out.println(me.getValue());
            return res;

Log in to reply

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