LeetCode: Third Maximum Number Solution

Sort unique numbers

Approach

Filter unique numbers

Sort that array

If there is the 3rd element, get it, else get the 1st one

Implementation

1/**
2 * @param {number[]} nums
3 * @return {number}
4 */
5var thirdMax = function (nums) {
6 const uniqueNums = [...new Set(nums)]
7 uniqueNums.sort((a, b) => b - a)
8
9 return uniqueNums[2] !== undefined ? uniqueNums[2] : uniqueNums[0]
10}

Comments

Loading comments...

Tags

leetcode

array

sorting

hash table

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Height Checker

Clone and sort

Previous Post

HoningJS

Search Posts