Algorithm
Problem Name: 414. Third Maximum Number
Problem Link: https://leetcode.com/problems/third-maximum-number/
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.
Example 1:
Input: nums = [3,2,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1.
Example 2:
Input: nums = [1,2] Output: 2 Explanation: The first distinct maximum is 2. The second distinct maximum is 1. The third distinct maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: nums = [2,2,3,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2 (both 2's are counted together since they have the same value). The third distinct maximum is 1.
Constraints:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int thirdMax(int[] nums) {
final double BASE_VALUE = ((double) Integer.MIN_VALUE) - 1;
double firstMax = BASE_VALUE;
double secMax = BASE_VALUE;
double thirdMax = BASE_VALUE;
for (int num : nums) {
if (num > firstMax) {
thirdMax = secMax;
secMax = firstMax;
firstMax = num;
}
else if (num > secMax && num < firstMax) {
thirdMax = secMax;
secMax = num;
}
else if (num > thirdMax && num < firstMax && num < secMax) {
thirdMax = num;
}
}
return thirdMax == BASE_VALUE ? (int) firstMax : (int) thirdMax;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const thirdMax = function(nums) {
let count = 0, max=mid=small=Number.MIN_SAFE_INTEGER;
for (let i in nums) {
if (count > 0 && nums[i] === max || count > 1 && nums[i] === mid) continue;
count++;
if (nums[i] > max) {
small = mid;
mid = max;
max = nums[i];
} else if (nums[i] > mid) {
small = mid;
mid = nums[i];
} else if (nums[i] > small) {
small = nums[i];
}
}
return count < 3 ? max : small;
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s=list(set(nums))
if s[-1]=0]
if len(s)>=3: return s[-3]
else: return s[-1]
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
using System;
namespace LeetCode
{
public class _0414_ThirdMaximumNumber
{
public int ThirdMax(int[] nums)
{
Array.Sort(nums);
int findMax = 0;
for (int i = nums.Length - 1; i > 0; i--)
{
if (nums[i] != nums[i - 1])
{
findMax++;
if (findMax == 2)
return nums[i - 1];
}
}
return nums[nums.Length - 1];
}
}
}
Copy The Code &
Try With Live Editor
Input
Output