[LeetCode] 238. Product of Array Except Self

2025. 3. 24. 00:04·코딩테스트/Python
728x90
반응형

🔗 Problem Link

https://leetcode.com/problems/product-of-array-except-self/


❔Thinking

  • 배열이 주어지면, 자신의 원소를 제외한 모든 원소의 곱을 배열에 담아 반환한다.
  • 나누기 연산 없이, O(n)의 시간복잡도를 가지는 알고리즘을 작성해야 한다.

💻Solution

def productExceptSelf(self, nums: List[int]) -> List[int]:
    left, right = 1, 1
    n = len(nums)
    answer = [1] * n
    for i in range(n):
        answer[i] *= left
        left *= nums[i]
    for i in range(n-1, -1, -1):
        answer[i] *= right
        right *= nums[i]
    return answer

🗝️keypoint

  1. 자신을 제외한 원소의 곱은, 자신을 기준으로 왼쪽과 오른쪽의 값을 모두 곱하는것이다.
  2. 나누기 연산을 사용할 수 있는 경우에도, 0으로 나누는 경우가 발생하기 때문에 유의해야 한다.
저작자표시 (새창열림)

'코딩테스트 > Python' 카테고리의 다른 글

[Programmers] Level 2. 아날로그 시계  (0) 2025.03.26
[LeetCode] 443. String Compression  (0) 2025.03.26
[LeetCode] 345. Reverse Vowels of a String  (0) 2025.03.19
[LeetCode] 605. Can Place Flowers  (0) 2025.03.18
[LeetCode] 1768. Merge Strings Alternately  (0) 2025.02.26
'코딩테스트/Python' 카테고리의 다른 글
  • [Programmers] Level 2. 아날로그 시계
  • [LeetCode] 443. String Compression
  • [LeetCode] 345. Reverse Vowels of a String
  • [LeetCode] 605. Can Place Flowers
swwho
swwho
일상을 데이터화하다
  • swwho
    하루한장
    swwho
  • 전체
    오늘
    어제
    • 분류 전체보기 (188)
      • ML_DL (39)
        • MUJAKJUNG (무작정 시리즈) (18)
        • 딥러닝 공부하기 (21)
      • 데이터사이언스 (1)
        • EDA (1)
        • 데이터과학을 위한 통계 (0)
      • 데이터엔지니어링 (2)
      • 논문리뷰 (2)
        • Computer Vision (2)
      • Python 활용하기 (12)
      • 코딩테스트 (127)
        • Python (109)
        • MySQL (14)
      • Git (3)
      • MySQL 활용하기 (0)
      • 일상 이야기 (1)
  • 블로그 메뉴

    • 홈
    • 태그
  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
swwho
[LeetCode] 238. Product of Array Except Self
상단으로

티스토리툴바