JAVA solution using TreeMap beats 81%


  • 0
    B
    class Solution {
        public int findLongestChain(int[][] pairs) {
            Map<Integer, Integer> map = new TreeMap<>();
            for(int i =0;i<pairs.length;i++){
                int end = map.getOrDefault(pairs[i][0], Integer.MAX_VALUE);
                if(pairs[i][1]<end){
                    map.put(pairs[i][0], pairs[i][1]);
                }
            }
            int preEnd = Integer.MIN_VALUE;
            int count = 0;
            for(Map.Entry<Integer, Integer> entry: map.entrySet()){
                int start = entry.getKey();
                int end = entry.getValue();
                if(start>preEnd){
                    count++;
                    preEnd = end;
                }else if(end<preEnd){
                    preEnd = end;
                }
            }
            return count;
        }
    }
    

Log in to reply
 

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