• 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

  • 相关阅读:
    微信跳一跳Python辅助无需配置一键操作
    人工智能三:机器学习、人工智能学习自学资料路线计划
    mysql安装配置、主从复制配置详解
    kafka安装使用配置1.1
    azkaban安装步骤
    flume安装
    zookeeper知识
    zookeeper安装
    mysql语法难点
    mysql安装
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4899729.html
Copyright © 2020-2023  润新知