Climbing the Leaderboard

  • + 0 comments

    Java 8 - Uses the stream distince and a modified binary search search algorithem.

        public static List<Integer> climbingLeaderboard(List<Integer> ranked, List<Integer> player) {
            List<Integer> playerRanking = new ArrayList<Integer>();
            List<Integer> rankBins = ranked.stream().distinct().collect(Collectors.toList());
            
            for (Integer score: player) {
                playerRanking.add(rank(rankBins, score));
            }
            
            return playerRanking;
        }
        
        private static Integer rank(List<Integer> r, Integer s) {
            if (s>r.get(0)) {
                r.add(0,s);
                return 1;
            }
    
            if (s<r.get(r.size()-1)) {
                r.add(s);
                return r.size();
            }
    
            int l = 0; 
            int h = r.size()-1;
            int m = l+((h-l)/2);
            
            while(h-l>1) {
                if ( s < r.get(m) )
                    l=m;
                else
                    h=m;
                m = l+((h-l)/2);
            }
            
            int vl = r.get(l);
            int vh = r.get(h);
            if (s == vl) {
                return l+1 ;
            } else if (s == vh) {
                return h+1;
            } else {
                r.add(h, s) ;
                return h+1;
            }
        }