Simple JavaScript Solution


  • 0
    /**
     * @param {number[]} nums
     * @return {number}
     */
    var findLHS = function(nums) {
      let numMap = {};
      nums.forEach(num => {
        if (numMap[num]) {
          ++numMap[num];
        } else {
          numMap[num] = 1;
        }
      });
      let keys = Object.keys(numMap).sort((a,b) => a-b);
      if (keys.length === 1) {
        return 0;
      }
      let max = 0;
      for(i = 0; i < keys.length - 1; ++i) {
        if ((keys[i+1] - keys[i] == 1) && (numMap[keys[i]] + numMap[keys[i+1]])> max) {
          max =numMap[keys[i]] + numMap[keys[i+1]];
        }
      }
      return max;
    };

Log in to reply
 

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