• [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 }
  • 相关阅读:
    题解 CF577B 【Modulo Sum】
    题解 P2827 【蚯蚓】
    题解 P1219 【八皇后】
    flash小实验
    URL编解码
    速记:两个进程模拟模态窗口
    youtube weburl后缀
    给ListView的条目自绘边框
    flash全屏在Activex控件上和在Google chrome插件上的区别
    ListView的消息钩子
  • 原文地址:https://www.cnblogs.com/lz87/p/10041882.html
Copyright © 2020-2023  润新知