zoukankan      html  css  js  c++  java
  • Leetcode 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.)


    解题思路:

    参考答案。

    Because we cannot use division, so assume we have two integer arrays with the same length of nums, 

    int[] leftProd = new int[nums.length]; int[] rightProd = new int[nums.length],

    we store the product of all the left elements in leftProd and the product of all the right elements in rightProd,

    then the product of leftProd[i] and rightProd[i] will be the value we want to put into the result.

    Take the example of num[] = {2, 4, 3, 6}, then leftProd will be {1, 2, 8, 24} , and rightProd will be {72, 18, 6, 1}.


    Java code:

    public class Solution {
        public int[] productExceptSelf(int[] nums) {
            int[] result = new int[nums.length];
            for(int i = 0; i < nums.length; i++) {
                if( i == 0){
                    result[i] = 1;
                }else{
                    result[i] = result[i-1] * nums[i-1];
                }
            }
            int prod = 1;
            for(int i = nums.length-1; i >= 0; i--){
                result[i] *= prod;
                prod *= nums[i];
            }
            return result;
        }
    }

    Reference:

    1. https://leetcode.com/discuss/46150/java-o-n-solution-no-extra-space-with-explanation

  • 相关阅读:
    ## js 性能 (未完。。。)
    React 创建元素的几种方式
    Json 与 javascript 对象的区别
    js 基本数据类型
    第十三章 事件
    第十二章 DOM2和DOM3
    第十一章 DOM扩展
    第十章 DOM
    第八章 BOM
    第七章 函数表达式
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4899729.html
Copyright © 2011-2022 走看看