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

  • 相关阅读:
    新手学习FFmpeg
    新手学习FFmpeg
    新手学习FFmpeg
    进阶计划
    面试题汇总
    grep命令
    Quartz教程三:Job与JobDetail介绍
    spring boot热部署
    Quartz学习——SSMM(Spring+SpringMVC+Mybatis+Mysql)和Quartz集成详解(四)
    SpringBoot集成篇(二) 异步调用Async
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4899729.html
Copyright © 2011-2022 走看看