deda
Deda의 데이터 디자인
deda
전체 방문자
오늘
어제
  • 분류 전체보기 (121)
    • Python (27)
      • Python 기초 (17)
      • Python 데이터분석 (10)
    • SQL (9)
    • Coding test (54)
      • Python 기초문제 (45)
      • LeetCode (9)
    • BigData (2)
    • ZeroBase (3)
    • UX (0)
    • Business Review (1)
    • 통계 & 수학 (17)
      • 통계학 (14)
      • 수학 (3)
    • 스터디 (6)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 네카라쿠배
  • 계차수열
  • 빅데이터
  • 계산기
  • matplotlib
  • SQL
  • 소인수분해
  • BMI
  • 제로베이스
  • 마이데이터
  • 데이터사이언티스트
  • 프로그래밍
  • 기초수학
  • 군수열
  • 통계
  • 등비수열
  • 데이터분석
  • 릿코드
  • 등차수열
  • 미니콘다
  • 모듈
  • 부트캠프
  • 데이터엔지니어
  • 파이썬
  • 데이터분석가
  • 팩토리얼
  • 최소공배수
  • 코딩
  • pandas
  • 함수

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
deda

Deda의 데이터 디자인

[LeetCode] Third Maximum Number
Coding test/LeetCode

[LeetCode] Third Maximum Number

2022. 5. 20. 16:58

🔍  문제

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
    'Coding test/LeetCode' 카테고리의 다른 글
    • [LeetCode] Find All Numbers Disappeared in an Array
    • [LeetCode] Max Consecutive Ones II
    • [LeetCode] Height Checker
    • [LeetCode] Move Zeroes
    deda
    deda
    데이터 분석 / 파이썬 / UX / 정량리서치

    티스토리툴바