Home > Mobile >  Third Maximum Number in Leetcode-javaScript
Third Maximum Number in Leetcode-javaScript

Time:03-04

Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number. Input: nums = [2,2,3,1] Output: 1

my code:

var thirdMax = function(nums) {
     let tempArr =new Set(nums.sort((a,b) => b-a));
     let newArr = Array.from(tempArr);

  return newArr[2];
  
};

In console it works, but return undefined. May I ask what I'm missing here? Thank you.

CodePudding user response:

May I ask what I'm missing here?

You are missing this part of the challenge:

If the third maximum does not exist, return the maximum number

Your code is looking for a third entry that might not exist (hence undefined). You'll need to test your code with input that only has 2 or 1 unique value(s), and adapt your code accordingly.

If you can't find how to do that, here is the spoiler:

return newArr[2] ?? newArr[0];

Note that slice expects a numeric argument (not a string). You can just omit that argument.

  • Related