問題描述
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
給定一個有n個整數的數組,其中n個>爲1,返回一個數組輸出,使得輸出[i]等於除了nums[i]之外的所有nums元素的乘積。
約束:保證數組的任何前綴或後綴(包括整個數組)的元素的乘積符合32位整數。
注意:請用O(n)代替除法求解。
跟進:
你能不能用常數空間複雜度來解它?(爲了分析空間複雜性,輸出數組不算作額外的空間。)
舉例
輸入: [1,2,3,4]
輸出: [24,12,8,6]
Python 實現
實現一:除法。
很直接的思路,先把所有元素的乘積計算出來,然後分別除以每個元素就能得到相應的結果(雖然這不是題目要求的解法),其中需要特別考慮到, 當元素值爲 0 時的處理。全程遍歷了兩次列表,除去 output 這個列表所佔的空間,這個過程的時間複雜度爲 O(N),空間複雜度爲 O(1)。
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# Method 1: Division.
product = 1
output = []
zero_cnt = 0
for num in nums:
if num != 0:
product *= num
else:
zero_cnt += 1
for i in range(len(nums)):
if nums[i] == 0:
if zero_cnt == 1:
output.append(product)
else:
output.append(0)
else:
if zero_cnt != 0:
output.append(0)
else:
output.append(product/nums[i])
return output
解法二
同樣是遍歷兩次列表,但是這個解法是先從左到右遍歷一次,再從右到左遍歷一次。其中第一次遍歷時,依次計算出到當前元素爲止,前面所有元素的乘積;第二次遍歷則把除自身以外的其他右邊的元素乘上,從而得到最終的結果。下面的表格可以幫助理解(爲了更好的表示,我用字母abcdefg代表各個元素的乘積)。
index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 備註 |
nums | a | b | c | d | e | f | g | |
output (第一次遍歷) | 1 | a | ab | abc | abcd | abcde | abcdef | 從左到右 |
right_product | bcdefg | cdefg | defg | efg | fg | g | 1 | 從右到左 |
output (第二次遍歷) = output (第一次遍歷) * right_product |
bcdefg | acdefg | abdefg | abcefg | abcdfg | abcdeg | abcdef |
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# Method 2.
n = len(nums)
output = [1]
# Product of the first n-1 elements (from left to right).
for i in range(n-1):
output.append(nums[i]*output[i])
# Multiply the left rest elements (from right to right).
right_product = nums[-1]
for i in range(n-1, 0, -1):
output[i-1] *= right_product
right_product *= nums[i-1]
return output
鏈接:https://leetcode.com/problems/product-of-array-except-self/