JS Solution (Sort)


  • 0
    C
    /**
     * @param {number[]} nums
     * @return {number}
     */
    var findLHS = function(nums) {
    	if(nums.length === 0) return 0;
    	var sNums = Array.from(nums).sort(function(a,b){return a-b;});
    	var start = 0;
    	var ret = 0, counter = 0, same = true, tmp = sNums[start];
    	var i = start;
    	while(i < sNums.length){
    		if(sNums[i] === tmp || sNums[i] === tmp+1){
    			if(sNums[i] !== tmp) {
    				if(start === 0) start = i;
    				same=false;
    			}
    			counter += 1;
    			i += 1;
    		} else {
    			if(counter > ret && !same) ret = counter;
    			if(start !== 0) i = start
    			counter = 0;
    			same = true;
    			tmp = sNums[i];
    			start = 0;
    		}
    	}
    	if(counter > ret && !same) ret = counter;
    	return ret;
    };
    

Log in to reply
 

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