Third Maximum Number
Easy arrays · sorting
Description
Constraints
1 <= n <= 100000
Examples
Input: nums = [3,2,1]
Output: 1
Hints (1)
- Deduplicate and take the third element after sorting descending.
Solutions
Dedup and sort. (requires "sort") · Time O(n log n) · Space O(n)
func thirdMax(nums []int) int {
seen := map[int]bool{}
u := []int{}
for _, n := range nums {
if !seen[n] {
seen[n] = true
u = append(u, n)
}
}
sort.Sort(sort.Reverse(sort.IntSlice(u)))
if len(u) >= 3 {
return u[2]
}
return u[0]
}
Dedup and sort. · Time O(n log n) · Space O(n)
function thirdMax(nums) {
const u = [...new Set(nums)].sort((a, b) => b - a);
return u.length >= 3 ? u[2] : u[0];
}
Dedup and sort. · Time O(n log n) · Space O(n)
function thirdMax($nums) {
$u = array_values(array_unique($nums));
rsort($u);
return $u[2] ?? $u[0];
}
Dedup and sort. · Time O(n log n) · Space O(n)
def thirdMax(nums):
u = sorted(set(nums), reverse=True)
return u[2] if len(u) >= 3 else u[0]
Dedup and sort. · Time O(n log n) · Space O(n)
function thirdMax(nums: number[]): number {
const u = [...new Set(nums)].sort((a, b) => b - a);
return u.length >= 3 ? u[2] : u[0];
}
Create a free account to submit solutions, track progress and save problems.
Create account