Java TreeSet + Comparator


  • 0
    M

    The ability to quickly create and use a Comparator is still a valuable skill -- makes it very easy to bind values together and create custom compare methods (even if this one was fairly simple):

    class Solution {
        
        public String[] findRelativeRanks(int[] nums) {
    
            TreeSet<Pair> set = new TreeSet<Pair>(new PairCompare());
            
            for(int i=0;i<nums.length;i++){
                
                set.add(new Pair(i, nums[i]));
                
            }
            
            String[] tr = new String[nums.length];
            
            int count = 0;
            
            while(set.size() > 0){
                
                Pair current = set.pollLast();
                
                if(count == 0){
                    
                    tr[current.index] = "Gold Medal";
                    
                }else if(count == 1){
                    
                    tr[current.index] = "Silver Medal";
                    
                }else if(count == 2){
                    
                    tr[current.index] = "Bronze Medal";
                    
                }else{
                    
                    tr[current.index] = (count+1)+"";
                    
                }
                
                count++;
                
            }
            
            return tr;
            
        }
        
    }
    
    class PairCompare implements Comparator<Pair>{
        
        public int compare(Pair a, Pair b){
            
            if(a.val > b.val) return 1;
            
            if(a.val < b.val) return -1;
            
            return a.index < b.index ? 1 : -1;
            
        }
        
    }
    
    class Pair{
        
        int index;
        
        int val;
        
        public Pair(int dex, int value){
            
            index = dex;
            
            val = value;
            
        }
        
    }

Log in to reply
 

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