일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 프로그래머스
- 109. Convert Sorted List to Binary Search Tree
- shiba
- data science
- 30. Substring with Concatenation of All Words
- 715. Range Module
- 파이썬
- concurrency
- 운영체제
- Class
- DWG
- Python Code
- Decorator
- Regular Expression
- iterator
- 43. Multiply Strings
- 315. Count of Smaller Numbers After Self
- 컴퓨터의 구조
- Python
- 시바견
- Protocol
- Generator
- Substring with Concatenation of All Words
- kaggle
- Python Implementation
- Convert Sorted List to Binary Search Tree
- LeetCode
- 밴픽
- t1
- attribute
Archives
- Today
- Total
Scribbling
LeetCode: 238. Product of Array Except Self 본문
Computer Science/Coding Test
LeetCode: 238. Product of Array Except Self
focalpoint 2021. 11. 25. 11:14Relatively straightforward solution, O(N) time O(1) Memory.
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
numZero, prod, zeroidx = 0, 1, 0
for i, num in enumerate(nums):
if num == 0:
numZero += 1
zeroidx = i
else:
prod *= num
if numZero >= 2:
return [0] * len(nums)
if numZero == 1:
ret = [0] * len(nums)
ret[zeroidx] = prod
return ret
# backward pass
ret = [0] * len(nums)
prod = 1
for i in range(len(nums)-1, -1, -1):
prod *= nums[i]
ret[i] = prod
# forward pass
prod = 1
for i, num in enumerate(nums):
prod *= num
nums[i] = prod
ret[0] = ret[1]
for i in range(1, len(nums)-1):
ret[i] = nums[i-1] * ret[i+1]
ret[-1] = nums[-2]
return ret
A solution based on fast recovery algorithm.
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
num_zeros = 0
all_product = 1
zero_idx = -1
for i, num in enumerate(nums):
if num == 0:
num_zeros += 1
zero_idx = i
else:
all_product *= num
if num_zeros >= 2:
return [0] * len(nums)
if num_zeros == 1:
ret = [0] * len(nums)
ret[zero_idx] = all_product
return ret
ret = []
for num in nums:
temp = self.fast_subtractor(abs(all_product), abs(num))
if not((all_product > 0) ^ (num > 0)):
ret.append(temp)
else:
ret.append(-temp)
return ret
def fast_subtractor(self, num, denom):
if denom == 1:
return num
ret = 0
now_denom = denom
now_share = 1
while now_denom <= num:
while now_denom <= num:
num -= now_denom
ret += now_share
now_denom *= 2
now_share *= 2
now_denom = denom
now_share = 1
return ret
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 134. Gas Station (0) | 2021.11.26 |
---|---|
LeetCode: 150. Evaluate Reverse Polish Notation (0) | 2021.11.26 |
LeetCode: 1329. Sort the Matrix Diagonally (0) | 2021.11.24 |
LeetCode: 1466. Reorder Routes to Make All Paths Lead to the City Zero (0) | 2021.11.23 |
LeetCode: 149. Max Points on a Line (0) | 2021.11.22 |