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)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

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

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
deda

Deda의 데이터 디자인

[LeetCode] Replace Elements with Greatest Element on Right Side
Coding test/LeetCode

[LeetCode] Replace Elements with Greatest Element on Right Side

2022. 5. 20. 15:01

🔍  문제

Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.

After doing so, return the array.

Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Explanation: 
- index 0 --> the greatest element to the right of index 0 is index 1 (18).
- index 1 --> the greatest element to the right of index 1 is index 4 (6).
- index 2 --> the greatest element to the right of index 2 is index 4 (6).
- index 3 --> the greatest element to the right of index 3 is index 4 (6).
- index 4 --> the greatest element to the right of index 4 is index 5 (1).
- index 5 --> there are no elements to the right of index 5, so we put -1.

 

🖥  실행

1) Answer

class Solution:
    def replaceElements(self, arr: List[int])
        for i, n in enumerate(arr):
            if i == len(arr)-1:
                arr[i] = -1
            else:    
                arr[i] = max(arr[i+1:])
        return arr

 

2) Better Solution

class Solution:
def replaceElements(self, arr: List[int])
        m = -1
        i = len(arr) -1 
        while i >= 0:
            temp = arr[i]
            arr[i] = m
            if temp > m:
                m = temp
            i-= 1
        return arr

 

'Coding test > LeetCode' 카테고리의 다른 글

[LeetCode] Height Checker  (0) 2022.05.20
[LeetCode] Move Zeroes  (0) 2022.05.20
[LeetCode] Valid Mountain Array  (0) 2022.05.20
[LeetCode] Merge Sorted Array  (0) 2022.05.20
[LeetCode] Find Numbers with Even Number of Digits  (0) 2022.05.20
    'Coding test/LeetCode' 카테고리의 다른 글
    • [LeetCode] Height Checker
    • [LeetCode] Move Zeroes
    • [LeetCode] Valid Mountain Array
    • [LeetCode] Merge Sorted Array
    deda
    deda
    데이터 분석 / 파이썬 / UX / 정량리서치

    티스토리툴바