O(n) JavaScript Solution


  • 0
    S
    /**
     * @param {string} version1
     * @param {string} version2
     * @return {number}
     */
    var compareVersion = function(version1, version2) {
        let v1Array = version1.split('.');
        let v2Array = version2.split('.');
        let len1 = v1Array.length;
        let len2 = v2Array.length;
        var i = Math.min(len1, len2);
    
        while(i > 0){
            var v1Elem = parseInt(v1Array.shift());
            var v2Elem = parseInt(v2Array.shift());
            if(v1Elem > v2Elem){
                return 1;
            } else if(v1Elem < v2Elem){
                return -1;
            }
            i--;
        }
        
        if(len1 > len2){
            if(parseInt(v1Array.join('')) > 0){
                return 1;
            }
        }else if(len1 < len2){
            if(parseInt(v2Array.join('')) > 0){
                return -1;
            }
        }
        
        return 0;
    };
    

Log in to reply
 

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