LeetCode 238:Product of Array Except Self

题意描述

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

测试用例

Example:

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

注意:不能使用除法

解题思路

一、思路一

  • 使用正向乘积与与逆向乘积。
  • 对于dp【i】而言,先计算出【0,i-1】的乘积
  • 然后逆向遍历,计算处【i+1,len】的乘积
    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;
        }
posted @ 2020-06-05 18:30  灵图  阅读(97)  评论(0编辑  收藏  举报