My Concise JavaScript Approach


  • 0
    T

    Most of the solutions are implemented in Java or C++. Please see my solution to this question.
    The approach is very concise and simple.

    1. Sort the Array first
    2. And discuss the different situations: 1. chainEnd[1] < curEle[0] 2. chainEnd[0] < curElement[0] && curElement[1] < chainEnd[1] 3. Other situations should be ignored.
    var findLongestChain = function(pairs) {
        //special case
        if(!pairs || pairs.length === 0){
            return 0;
        }
        //sort the array 
        pairs.sort(function(left, right){
           if(left[0] !== right[0]){
               return left[0] - right[0];
           }else{
               return left[1] - right[1];
           } 
        });
        
        let retMax = 1, begin = pairs[0][0], end = pairs[0][1];
        for(let i=1; i<pairs.length; i++){
            if(end < pairs[i][0]){
                retMax++;
                begin = pairs[i][0];
                end = pairs[i][1];
            }else if(begin < pairs[i][0] && pairs[i][1] < end){
                begin = pairs[i][0];
                end = pairs[i][1];
            }
        }
        return retMax;
    };
    
    • list item

Log in to reply
 

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