🔍 문제
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 = [3,2,1]
Output: 1
Explanation:
The first distinct maximum is 3.
The second distinct maximum is 2.
The third distinct maximum is 1.
🖥 실행
1) Answer
class Solution:
def thirdMax(self, nums: List[int]) -> int:
for i in nums:
while nums.count(i) > 1:
nums.remove(i)
nums.sort(reverse=True)
if len(nums)>2:
return nums[2]
else:
return max(nums)
2) Better Solution
class Solution(object):
def thirdMax(self, nums):
v = [float('-inf'), float('-inf'), float('-inf')]
for num in nums:
if num not in v:
if num > v[0]: v = [num, v[0], v[1]]
elif num > v[1]: v = [v[0], num, v[1]]
elif num > v[2]: v = [v[0], v[1], num]
return max(nums) if float('-inf') in v else v[2]
'Coding test > LeetCode' 카테고리의 다른 글
[LeetCode] Find All Numbers Disappeared in an Array (0) | 2022.05.23 |
---|---|
[LeetCode] Max Consecutive Ones II (0) | 2022.05.20 |
[LeetCode] Height Checker (0) | 2022.05.20 |
[LeetCode] Move Zeroes (0) | 2022.05.20 |
[LeetCode] Replace Elements with Greatest Element on Right Side (0) | 2022.05.20 |