搜索
首页Javajava教程Leetcode:除自身之外的数组的乘积

这个问题在线性时间和空间中看起来很容易解决。这个问题建立在数组的一些基本概念之上。

  1. 数组遍历。
  2. 前缀和后缀之和。

在编码面试中提出这个问题的公司有 Facebook、亚马逊、苹果、Netflix、谷歌、微软、Adobe 以及许多其他顶级科技公司。

问题陈述

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

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

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

测试用例#1

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

测试用例#2:

Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]

了解问题

这个问题在线性时间和空间上看起来更容易解决,但在编写伪代码或实际代码实现时却很棘手。

插图

让我们看看包含 4 个元素的简单数组的预期结果:

input = {1, 2, 3, 4}

因此,每个索引处的值是数组中除该值本身之外的所有其他元素的乘积。下图说明了这一点。

Leetcode : Product Of Array Except Self

根据上图,我们可以得出一个公式。对于任何给定的索引 i,我们可以使用从 o 到 (i - 1) 的元素的乘积加上从 (i + 1) 到 (N - 1) 的元素的乘积来找到该值。如下图所示:

Leetcode : Product Of Array Except Self

思维过程

在写伪代码之前,先提出问题并向面试官提问。

  1. 我应该担心重复吗?
  2. 如果数组为空或者只有一个元素怎么办?预期结果是什么?
  3. 我应该考虑/忽略数组中任何索引中的 0 值吗?因为除了包含 0 的索引之外,所有其他值都为 0。
  4. 这个问题的极端/边缘情况是什么?

一旦你和面试官讨论了上述问题,就想出各种方法来解决问题。

  1. 天真的方法/暴力。
  2. 所有元素的乘积。
  3. 左右产品。
  4. 前缀和后缀总和。

方法 1:朴素/暴力

直觉

要采用强力方法,我们必须执行两个 for 循环。当外循环索引与内循环索引值匹配时,我们应该跳过乘积;否则,我们将继续使用该产品。

Leetcode : Product Of Array Except Self

算法

  1. 初始化变量:
    • N = nums.length(输入数组的长度)。
    • result = new int[N] (存储结果的数组)。
  2. 外循环(迭代 nums 中的每个元素):
    • 对于 i = 0 到 N-1:初始化 currentProduct = 1。
  3. 内循环(计算当前元素的乘积),对于 j = 0 到 N-1:
    • 如果 i == j,则使用 continue 跳过当前迭代。
    • 将 currentProduct 乘以 nums[j]。
    • 将 currentProduct 分配给 result[i]。
  4. 返回结果。

代码

// brute force
static int[] bruteForce(int[] nums) {
    int N = nums.length;
    int[] result = new int[N];

    for (int i = 0; i 



<h3>
  
  
  复杂性分析
</h3>

<ol>
<li>
<strong>时间复杂度</strong>:O(n^2),用于在外循环和内循环中迭代数组两次。</li>
<li>
<strong>空间复杂度</strong>:O(n),对于我们使用的辅助空间(result[]数组)。</li>
</ol>

<h2>
  
  
  方法 2:数组 ❌ 的乘积
</h2>

<p>大多数开发人员认为的一种方法是运行所有元素的乘积和,将乘积和除以每个数组值,然后返回结果。</p>

<h3>
  
  
  伪代码
</h3>



<pre class="brush:php;toolbar:false">// O(n) time and O(1) space
p = 1
for i -> 0 to A[i]
  p * = A[i]
for i -> 0 to (N - 1)
  A[i] = p/A[i] // if A[i] == 0 ? BAM error‼️  

代码

// code implementation
static int[] productSum(int[] nums) {
    int product_sum = 1;
    for(int num: nums) {
        product_sum *= num;
    }

    for(int i = 0; i 



<p>如果数组元素之一包含 0 怎么办? ?</p>

<p>除了包含0的索引之外,所有索引的值肯定是无穷大。另外,代码会抛出 java.lang.ArithmeticException。<br>
</p>

<pre class="brush:php;toolbar:false">Exception in thread "main" java.lang.ArithmeticException: / by zero
    at dev.ggorantala.ds.arrays.ProductOfArrayItself.productSum(ProductOfArrayItself.java:24)
    at dev.ggorantala.ds.arrays.ProductOfArrayItself.main(ProductOfArrayItself.java:14)

方法 3:查找前缀和后缀乘积

在我的网站上的数组掌握课程中了解有关前缀和后缀和的更多信息 https://ggorantala.dev

直觉与公式

前缀和后缀是在为结果编写算法之前计算的。前缀和后缀总和公式如下:

Leetcode : Product Of Array Except Self

Algorithm Steps

  1. Create an array result of the same length as nums to store the final results.
  2. Create two additional arrays prefix_sum and suffix_sum of the same length as nums.
  3. Calculate Prefix Products:
    • Set the first element of prefix_sum to the first element of nums.
    • Iterate through the input array nums starting from the second element (index 1). For each index i, set prefix_sum[i] to the product of prefix_sum[i-1] and nums[i].
  4. Calculate Suffix Products:
    • Set the last element of suffix_sum to the last element of nums.
    • Iterate through the input array nums starting from the second-to-last element (index nums.length - 2) to the first element. For each index i, set suffix_sum[i] to the product of suffix_sum[i+1] and nums[i].
  5. Calculate the result: Iterate through the input array nums.
    • For the first element (i == 0), set result[i] to suffix_sum[i + 1].
    • For the last element (i == nums.length - 1), set result[i] to prefix_sum[i - 1].
    • For all other elements, set result[i] to the product of prefix_sum[i - 1] and suffix_sum[i + 1].
  6. Return the result array containing the product of all elements except the current element for each index.

Pseudocode

Function usingPrefixSuffix(nums):
    N = length of nums
    result = new array of length N
    prefix_sum = new array of length N
    suffix_sum = new array of length N

    // Calculate prefix products
    prefix_sum[0] = nums[0]
    For i from 1 to N-1:
        prefix_sum[i] = prefix_sum[i-1] * nums[i]

    // Calculate suffix products
    suffix_sum[N-1] = nums[N-1]
    For i from N-2 to 0:
        suffix_sum[i] = suffix_sum[i+1] * nums[i]

    // Calculate result array
    For i from 0 to N-1:
        If i == 0:
            result[i] = suffix_sum[i+1]
        Else If i == N-1:
            result[i] = prefix_sum[i-1]
        Else:
            result[i] = prefix_sum[i-1] * suffix_sum[i+1]

    Return result

Code

// using prefix and suffix arrays
private static int[] usingPrefixSuffix(int[] nums) {
    int[] result = new int[nums.length];

    int[] prefix_sum = new int[nums.length];
    int[] suffix_sum = new int[nums.length];

    // prefix sum calculation
    prefix_sum[0] = nums[0];
    for (int i = 1; i = 0; i--) {
        suffix_sum[i] = suffix_sum[i + 1] * nums[i];
    }

    for (int i = 0; i 



<h3>
  
  
  Complexity analysis
</h3>

<ol>
<li>
<strong>Time complexity</strong>: The time complexity of the given code is O(n), where n is the length of the input array nums. This is because:

<ul>
<li>Calculating the prefix_sum products take O(n) time.</li>
<li>Calculating the suffix_sum products take O(n) time.</li>
<li>Constructing the result array takes O(n) time.</li>
</ul>
</li>
</ol>

<p>Each of these steps involves a single pass through the array, resulting in a total time complexity of O(n)+O(n)+O(n) = 3O(n), which is O(n).</p>

<ol>
<li>
<strong>Space complexity</strong>: The space complexity of the given code is O(n). This is because:

<ul>
<li>The prefix_sum array requires O(n) space.</li>
<li>The suffix_sum array requires O(n) space.</li>
<li>Theresult array requires O(n) space.
All three arrays are of length n, so the total space complexity is O(n) + O(n) + O(n) = 3O(n), which is O(n).</li>
</ul>
</li>
</ol>

<h3>
  
  
  Optimization ?
</h3>

<p>For the suffix array calculation, we override the input nums array instead of creating one.<br>
</p>

<pre class="brush:php;toolbar:false">private static int[] usingPrefixSuffixOptimization(int[] nums) {
    int[] result = new int[nums.length];

    int[] prefix_sum = new int[nums.length];

    // prefix sum calculation
    prefix_sum[0] = nums[0];
    for (int i = 1; i = 0; i--) {
        nums[i] = nums[i + 1] * nums[i];
    }

    for (int i = 0; i 



<p>Hence, we reduced the space of O(n). Time and space are not reduced, but we did a small optimization here.</p>

<h2>
  
  
  Approach 4: Using Prefix and Suffix product knowledge ?
</h2>

<h3>
  
  
  Intuition
</h3>

<p>This is a rather easy approach when we use the knowledge of prefix and suffix arrays.</p>

<p>For every given index i, we will calculate the product of all the numbers to the left and then multiply it by the product of all the numbers to the right. This will give us the product of all the numbers except the one at the given index i. Let's look at a formal algorithm that describes this idea more clearly.</p>

<h3>
  
  
  Algorithm steps
</h3>

<ol>
<li>Create an array result of the same length as nums to store the final results.</li>
<li>Create two additional arrays prefix_sum and suffix_sum of the same length as nums.</li>
<li>Calculate Prefix Products:

<ul>
<li>Set the first element of prefix_sum to 1.</li>
<li>Iterate through the input array nums starting from the second element (index 1). For each index i, set prefix_sum[i] to the product of prefix_sum[i - 1] and nums[i - 1].</li>
</ul>
</li>
<li>Calculate Suffix Products:

<ul>
<li>Set the last element of suffix_sum to 1.</li>
<li>Iterate through the input array nums starting from the second-to-last element (index nums.length - 2) to the first element.</li>
<li>For each index i, set suffix_sum[i] to the product of suffix_sum[i + 1] and nums[i + 1].</li>
</ul>
</li>
<li>Iterate through the input array nums.

<ul>
<li>For each index i, set result[i] to the product of prefix_sum[i] and suffix_sum[i].</li>
</ul>
</li>
<li>Return the result array containing the product of all elements except the current element for each index.</li>
</ol>

<h3>
  
  
  Pseudocode
</h3>



<pre class="brush:php;toolbar:false">Function prefixSuffix1(nums):
    N = length of nums
    result = new array of length N
    prefix_sum = new array of length N
    suffix_sum = new array of length N

    // Calculate prefix products
    prefix_sum[0] = 1
    For i from 1 to N-1:
        prefix_sum[i] = prefix_sum[i-1] * nums[i-1]

    // Calculate suffix products
    suffix_sum[N-1] = 1
    For i from N-2 to 0:
        suffix_sum[i] = suffix_sum[i+1] * nums[i+1]

    // Calculate result array
    For i from 0 to N-1:
        result[i] = prefix_sum[i] * suffix_sum[i]

    Return result

Code

private static int[] prefixSuffixProducts(int[] nums) {
    int[] result = new int[nums.length];

    int[] prefix_sum = new int[nums.length];
    int[] suffix_sum = new int[nums.length];

    prefix_sum[0] = 1;
    for (int i = 1; i = 0; i--) {
        suffix_sum[i] = suffix_sum[i + 1] * nums[i + 1];
    }

    for (int i = 0; i 



<h3>
  
  
  Complexity analysis
</h3>

<ol>
<li>
<strong>Time complexity</strong>: The time complexity of the given code is O(n), where n is the length of the input array nums. This is because:

<ul>
<li>Calculating the prefix_sum products take O(n) time.</li>
<li>Calculating the suffix_sum products take O(n) time.</li>
<li>Constructing the result array takes O(n) time.</li>
</ul>
</li>
</ol>

<p>Each of these steps involves a single pass through the array, resulting in a total time complexity of O(n)+O(n)+O(n) = 3O(n), which is O(n).</p>

<ol>
<li>
<strong>Space complexity</strong>: The space complexity of the given code is O(n). This is because:

<ul>
<li>The prefix_sum array requires O(n) space.</li>
<li>The suffix_sum array requires O(n) space.</li>
<li>The result array requires O(n) space.</li>
</ul>
</li>
</ol>

<p>All three arrays are of length n, so the total space complexity is O(n) + O(n) + O(n) = 3O(n), which is O(n).</p>

<h2>
  
  
  Approach 5: Carry Forward technique
</h2>

<h3>
  
  
  Intuition
</h3>

<p>The carry forward technique optimizes us to solve the problem with a more efficient space complexity. Instead of using two separate arrays for prefix and suffix products, we can use the result array itself to store intermediate results and use a single pass for each direction.</p>

<p>Here’s how you can implement the solution using the carry-forward technique:</p>

<h3>
  
  
  Algorithm Steps for Carry Forward Technique
</h3>

<ol>
<li>Initialize Result Array:

<ul>
<li>Create an array result of the same length as nums to store the final results.</li>
</ul>
</li>
<li>Calculate Prefix Products:

<ul>
<li>Initialize a variable prefixProduct to 1.</li>
<li>Iterate through the input array nums from left to right. For each index i, set result[i] to the value of prefixProduct. Update prefixProduct by multiplying it with nums[i].</li>
</ul>
</li>
<li>Calculate Suffix Products and Final Result:

<ul>
<li>Initialize a variable suffixProduct to 1.</li>
<li>Iterate through the input array nums from right to left. For each index i, update result[i] by multiplying it with suffixProduct. Update suffixProduct by multiplying it with nums[i].</li>
</ul>
</li>
<li>Return the result array containing the product of all elements except the current element for each index.</li>
</ol>

<h3>
  
  
  Pseudocode
</h3>



<pre class="brush:php;toolbar:false">prefix products
    prefixProduct = 1
    For i from 0 to N-1:
        result[i] = prefixProduct
        prefixProduct = prefixProduct * nums[i]

    // Calculate suffix products and finalize result
    suffixProduct = 1
    For i from N-1 to 0:
        result[i] = result[i] * suffixProduct
        suffixProduct = suffixProduct * nums[i]

    Return result

Code

// carry forward technique
private static int[] carryForward(int[] nums) {
    int n = nums.length;
    int[] result = new int[n];

    // Calculate prefix products
    int prefixProduct = 1;
    for (int i = 0; i = 0; i--) {
        result[i] *= suffixProduct;
        suffixProduct *= nums[i];
    }
    return result;
}

Explanation

  1. Prefix Products Calculation:
    • We initialize prefixProduct to 1 and update each element of result with the current value of prefixProduct.
    • Update prefixProduct by multiplying it with nums[i].
  2. Suffix Products Calculation:
    • We initialize suffixProduct to 1 and update each element of result(which already contains the prefix product) by multiplying it with suffixProduct.
    • Update suffixProduct by multiplying it with nums[i].

Complexity analysis

  1. Time Complexity: O(n) time
  2. Space Complexity: O(n) (for the result array)

This approach uses only a single extra array (result) and two variables (prefixProduct and suffixProduct), achieving efficient space utilization while maintaining O(n) time complexity.

以上是Leetcode:除自身之外的数组的乘积的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
JVM性能与其他语言JVM性能与其他语言May 14, 2025 am 12:16 AM

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生产性。1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

Java平台独立性:使用示例Java平台独立性:使用示例May 14, 2025 am 12:14 AM

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允许CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

JVM架构:深入研究Java虚拟机JVM架构:深入研究Java虚拟机May 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM:JVM与操作系统有关吗?JVM:JVM与操作系统有关吗?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java:写一次,在任何地方跑步(WORA) - 深入了解平台独立性Java:写一次,在任何地方跑步(WORA) - 深入了解平台独立性May 14, 2025 am 12:05 AM

Java实现“一次编写,到处运行”通过编译成字节码并在Java虚拟机(JVM)上运行。1)编写Java代码并编译成字节码。2)字节码在任何安装了JVM的平台上运行。3)使用Java原生接口(JNI)处理平台特定功能。尽管存在挑战,如JVM一致性和平台特定库的使用,但WORA大大提高了开发效率和部署灵活性。

Java平台独立性:与不同的操作系统的兼容性Java平台独立性:与不同的操作系统的兼容性May 13, 2025 am 12:11 AM

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允许Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

什么功能使Java仍然强大什么功能使Java仍然强大May 13, 2025 am 12:05 AM

JavaispoperfulduetoitsplatFormitiondence,对象与偏见,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

顶级Java功能:开发人员的综合指南顶级Java功能:开发人员的综合指南May 13, 2025 am 12:04 AM

Java的顶级功能包括:1)面向对象编程,支持多态性,提升代码的灵活性和可维护性;2)异常处理机制,通过try-catch-finally块提高代码的鲁棒性;3)垃圾回收,简化内存管理;4)泛型,增强类型安全性;5)ambda表达式和函数式编程,使代码更简洁和表达性强;6)丰富的标准库,提供优化过的数据结构和算法。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。