LeetCode 238:Product of Array Except Self

时间:2020-06-05 19:08:02   收藏:0   阅读:51

题意描述

给定一个由n个整数组成的数组num,其中n> 1,则返回一个数组输出,使得output [i]等于除nums [i]之外所有nums元素的乘积。

测试用例

Example:

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

注意:不能使用除法

解题思路

一、思路一

    public static int[] productExceptSelf(int[] nums) {
            int n = nums.length;
            int[] res = new int[n];
            res[0] = 1;
        	//正向乘积,【0,i-1】的乘积
            for (int i = 1; i < n; i++) {
                res[i] = res[i - 1] * nums[i - 1];
            }
            int right = 1;	//使用临时遍历保存逆向乘积
            for (int i = n - 1; i >= 0; i--) {
                res[i] *= right;//正向乘积 *  逆向乘积
                right *= nums[i];//更新逆向乘积
            }
            return res;
        }

原文:https://www.cnblogs.com/le-le/p/13051335.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!