【LeetCode】237 Product of Array Except Self

来源:互联网 发布:网络拓扑结构的特点 编辑:程序博客网 时间:2024/05/08 02:56
Product of Array Except Self
Total Accepted: 388 Total Submissions: 1017 My Submissions Question Solution 
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.)
【解题思路】
1、数组每个位的数是其他数的乘积。
2、如果用除法,是不是很简单,分分钟搞定。
3、从左到右遍历一遍数组,第i位置的数,是前面k-1个数的乘积。
4、从右到左遍历一遍数组,第i位置的数,是它左边的乘积乘以右边的乘积。
5、所以,这个就是结果。

Java AC

public class Solution {    public int[] productExceptSelf(int[] nums) {        int len = nums.length;        int res[] = new int[len];        res[0] = 1;        for(int i = 1; i < len; i++){            res[i] = res[i-1] * nums[i-1];        }        int right = 1;        for(int i = len - 1; i >= 0; i--){            res[i] *= right;            right *= nums[i];        }        return res;    }}


0 0