Python 中数组除自身之外的乘积

pythonserver side programmingprogramming更新于 2025/11/22 23:40:17

假设我们有一个名为 nums 的数组,其中包含 n 个整数,其中 n > 1。我们必须找到一个数组输出,使得 output[i] 等于 nums 中除 nums[i] 之外的所有元素的乘积。因此,如果输入数组为 [1,2,3,4],则输出将为 [24,12,8,6]。我们必须在不使用除法运算符的情况下解决这个问题。

要解决这个问题,我们将遵循以下步骤 −

  • right_mul := 一个与 nums 大小相同的数组,用 0 填充它
  • right_mul 的最后一个元素 = nums 的最后一个元素
  • 对于 i,范围为 1 到 nums 的长度
    • right_mul[nums 的长度 – i – 1] = right_mul[nums 的长度 – i]* nums[nums 的长度 – i – 1]
  • 输出 := 一个与 nums 大小相同的数组,用 0 填充
  • 前缀 := 1,索引 := 0
  • 当索引 < 输出长度 – 1
    • 输出[索引] := 前缀 * right_mul[索引 + 1]
    • 前缀 := 前缀 * nums[索引]
    • 索引 := 索引 + 1
  • 输出的最后一个元素 := 前缀
  • 返回输出

让我们看看下面的实现以便更好地理解 −

示例

class Solution(object):
   def productExceptSelf(self, nums):
      right_multiply = [0] * len(nums)
      right_multiply[-1]=nums[-1]
      for i in range(1,len(nums)):
         right_multiply[len(nums)-i-1] = right_multiply[len(nums)-i] * nums[len(nums)-i-1]
      output = [0]*len(nums)
      prefix = 1
      current_index = 0
      while current_index < len(output)-1:
         output[current_index] = prefix * right_multiply[current_index+1]
         prefix *= nums[current_index]
         current_index +=1
      output[-1] = prefix
      return output
ob1 = Solution()
print(ob1.productExceptSelf([1,3,5,7,9]))

输入

[1,3,5,7,9]

输出

[945, 315, 189, 135, 105]

相关文章


有用资源