zoukankan      html  css  js  c++  java
  • [LeetCode] 238 Product of Array Except Self

    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].

    Example:

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

    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.)

     
    Solution 1. O(n) runtime, O(n) space 
     
     1 class Solution {
     2     public int[] productExceptSelf(int[] nums) {
     3         if(nums == null || nums.length <= 1) {
     4             return nums;
     5         }
     6         int[] leftProduct = new int[nums.length];
     7         leftProduct[0] = nums[0];
     8         for(int i = 1; i < nums.length; i++) {
     9             leftProduct[i] = leftProduct[i- 1] * nums[i];
    10         }
    11         int[] rightProduct = new int[nums.length];
    12         rightProduct[nums.length - 1] = nums[nums.length - 1];
    13         for(int i = nums.length - 2; i >= 0; i--) {
    14             rightProduct[i] = rightProduct[i + 1] * nums[i];
    15         }
    16         int[] productArray = new int[nums.length];
    17         productArray[0] = rightProduct[1];
    18         productArray[nums.length - 1] = leftProduct[nums.length - 2];
    19         for(int i = 1; i < nums.length - 1; i++) {
    20             productArray[i] = leftProduct[i - 1] * rightProduct[i + 1];
    21         }
    22         return productArray;
    23     }
    24 }

    Solution 2. O(n) runtime, O(1) space, using the output array to store partial left-product results, then update the final product results on a 2nd pass from right to left.

     1 class Solution {
     2     public int[] productExceptSelf(int[] nums) {
     3         if(nums == null || nums.length <= 1) {
     4             return nums;
     5         }
     6         int[] productArray = new int[nums.length];
     7         productArray[0] = 1;
     8         for(int i = 1; i < productArray.length; i++) {
     9             productArray[i] = productArray[i - 1] * nums[i - 1];
    10         }
    11         int rightProduct = nums[nums.length - 1];
    12         for(int i = productArray.length - 2; i >= 0; i--) {
    13             productArray[i] *= rightProduct;
    14             rightProduct *= nums[i];
    15         }
    16         return productArray;
    17     }
    18 }
  • 相关阅读:
    [leetcode-671-Second Minimum Node In a Binary Tree]
    [leetcode-667-Beautiful Arrangement II]
    棋盘从左上到右下最小初始值
    [leetcode-666-Path Sum IV]
    [leetcode-665-Non-decreasing Array]
    [leetcode-215-Kth Largest Element in an Array]
    LINQ简记(3):子句
    技巧篇:如何重写基类的事件
    技巧篇:结合反射技术实现多算法动态加密
    龙年新作:水印文字添加工具源码摘要
  • 原文地址:https://www.cnblogs.com/lz87/p/10041882.html
Copyright © 2011-2022 走看看