[LeetCode] 238. Product of Array Except Self
2021. 1. 10. 23:22ㆍProblem Solving/LeetCode
https://leetcode.com/problems/product-of-array-except-self/
Product of Array Except Self - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
풀이
from typing import List class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: left = [] right = [] result = [] # 왼쪽 곱셈 tmp = 1 for i in range(len(nums)): if i == 0: left.append(tmp) else: tmp *= nums[i-1] left.append(tmp) # 오른쪽 곱셈 tmp = 1 for i in range(len(nums) - 1, -1, -1): if i == len(nums) - 1: right.append(tmp) else: tmp *= nums[i+1] right.append(tmp) right = right[::-1] for i in range(len(left)): result.append(left[i] * right[i]) return result
왼쪽곱셈, 오른쪽곱셈으로 나누어서 그 리스트들의 원소들을 각각 곱하여 구했다.
책 풀이가 약 100ms 더 빠르다. out을 재 활용하기 때문이다

책 정보
![]() |
|
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
[LeetCode] 234. Palindrome Linked List (0) | 2021.01.12 |
---|---|
[LeetCode] 121. Best Time to Buy and Sell Stock (0) | 2021.01.11 |
[LeetCode] 561. Array Partition I (0) | 2021.01.10 |
[LeetCode] 15. 3Sum (0) | 2021.01.10 |
[LeetCode] 1. Two Sum (1) | 2021.01.07 |