150强访谈简单

除自身之外的数组的乘积

“除自体之外的数组的乘积”问题的详细指南和 Python 实现。

问题陈述

简单

给定一个整数数组 nums,返回一个数组 answer,使得 answer[i] 等于 nums 中除 nums[i] 之外的所有元素的乘积。

nums 的任何前缀或后缀的乘积保证适合 32 位整数。

您必须编写一个在 O(n) 时间内运行且不使用除法运算的算法。

编写一个函数 productExceptSelf(nums: List[int]) -> List[int]

约束条件
  • 2 <= len(nums) <= 10^5
  • -30 <= nums[i] <= 30
  • The product of any prefix or suffix of nums fits in a 32-bit integer

示例

Example 1
Input
nums = [1, 2, 3, 4]
Output
[24, 12, 8, 6]
Explanation

answer[0] = 2*3*4 = 24, answer[1] = 1*3*4 = 12, answer[2] = 1*2*4 = 8, answer[3] = 1*2*3 = 6.

Example 2
Input
nums = [-1, 1, 0, -3, 3]
Output
[0, 0, 9, 0, 0]
Explanation

Any product that includes the 0 at index 2 becomes 0. answer[2] = (-1)*1*(-3)*3 = 9.

Need a Hint?
考虑使用数组和哈希特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。