zoukankan      html  css  js  c++  java
  • LeetCode 238. Product of Array Except Self (去除自己的数组之积)

    Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

    Solve it without division and in O(n).

    For example, given [1,2,3,4], return [24,12,8,6].

    Follow up:
    Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)


    题目标签:Array 

      题目给了我们一个 nums array, 让我们返回一个新的output array, 每一个项都是 整个数组除了自己项的乘积。题目规定了不能用除法,而且要O(n) 和 constant space complexity。

      来分析一下,每一个数字 都需要除了自己以外的 所有数的 乘积。 那么可以从另一个角度来看, 每一个数字, 需要自己位置 左边的所有数字 乘积 * 右边的所有数字 乘积。

      我们可以通过两次遍历数组来实现这个目标:

      首先把output[0] 设为1, 方便*;

      第一次遍历,从第二个数字到最后一个数字: 把output里每一个数字 = nums这个数字 左边 的所有数字的乘积;结束后可以发现,output里最后一个数字的 乘积 已经完成了,因为最后一个数字 没有右边的数字;

      第二次遍历,从倒数第二个数字到第一个数字, 并且设一个product = nums 里最后一个数字: 把output里每一个数字 * product,还要更新product = product * nums里数字,这一次遍历相当于把每一个数字的剩下右边所有数字乘积补上。

      举例来看一下:

      [2, 3, 4, 5]  nums

      [1, 0, 0, 0]  output

      第一次遍历:

      [1, 2, 0, 0] 

      [1, 2, 6, 0]

      [1, 2, 6, 24]     结束第一次遍历;可以看出,第一次遍历同样有一个product 值,只不过直接保存在output里而已。

      第二次遍历:    product = 5;

      [1, 2, 30, 24]   更新product = 5 * 4;

      [1, 40, 30, 24]    更新product = 5 *4 * 3;

      [60, 40, 30, 24]  结束。

        

    Java Solution:

    Runtime beats 29.29% 

    完成日期:09/07/2017

    关键词:Array

    关键点:来回遍历两次   第一次从左到右 -> 把每一个数字 等于 这个数字左边的所有数字的乘积;

                 第二次从右到左 -> 把每一个数字 剩余的 右边所有数字乘积 补上

     1 class Solution 
     2 {
     3     public int[] productExceptSelf(int[] nums) 
     4     {
     5         // create output array
     6         int [] output = new int[nums.length];
     7         // make first number to 1
     8         output[0] = 1;
     9         
    10         // 1st iteration from 1 ~ end -> make each nums[i] = 0 ~ i-1 numbers product
    11         for(int i=1; i<nums.length; i++)
    12             output[i] = nums[i-1] * output[i-1];
    13         
    14         
    15         int product = nums[nums.length-1];
    16         // 2nd iteration from end - 2 ~ 0 -> make each nums[i] * (i+1 ~ end) numbers product 
    17         for(int i=nums.length-2; i>=0; i--)
    18         {
    19             output[i] *= product;
    20             product *= nums[i];
    21         }
    22         
    23         return output;
    24     }
    25 }

    参考资料:N/A

    LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  • 相关阅读:
    上下,流动
    面对离去了的亲人,
    计算 star 之间 距离,
    咀嚼,
    python中的内嵌函数
    python中全局变量和局部变量
    python中函数的闭包
    python中函数的收集参数
    python中如何将局部变量扩展为全局变量(global关键字)
    python中的内嵌函数
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7492905.html
Copyright © 2011-2022 走看看