leetcode 238. Product of Array Except Self

来源:互联网 发布:mac新建文本文档 编辑:程序博客网 时间:2024/06/16 01:58

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.)

这道题难点在于不能使用除法,想通了思路就很简单。然而我的解法并没有做到solve it without extra space.

package leetcode;import java.util.Arrays;public class Product_of_Array_Except_Self_238 {public int[] productExceptSelf(int[] nums) {int length=nums.length;int[] result=new int[length];int[] leftProduct=new int[length];//每个leftProduct[i]里存nums[0]~nums[i-1]的乘积int[] rightProduct=new int[length];//每个rightProduct[i]里存nums[i+1]~nums[length-1]的乘积leftProduct[0]=1;for(int i=1;i<length;i++){leftProduct[i]=leftProduct[i-1]*nums[i-1];}rightProduct[length-1]=1;for(int i=length-2;i>=0;i--){rightProduct[i]=rightProduct[i+1]*nums[i+1];}for(int i=0;i<length;i++){result[i]=leftProduct[i]*rightProduct[i];}return result;}public static void main(String[] args) {// TODO Auto-generated method stubProduct_of_Array_Except_Self_238 p=new Product_of_Array_Except_Self_238();int[] nums=new int[]{1,2,3,4};System.out.println(Arrays.toString(p.productExceptSelf(nums)));}}
有大神跟我想法一样,但是解法上并没有用到extra space.

public int[] productExceptSelf(int[] nums) {    int n = nums.length;    int[] res = new int[n];    res[0] = 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;}
另外一个大神也是差不多的想法:
The idea is simply. The product basically is calculated using the numbers before the current number and the numbers after the current number. Thus, we can scan the array twice. First, we calcuate the running product of the part before the current number. Second, we calculate the running product of the part after the current number through scanning from the end of the array.

public int[] productExceptSelf(int[] nums) {    int leng = nums.length;    int[] ret = new int[leng];    if(leng == 0)        return ret;    int runningprefix = 1;    for(int i = 0; i < leng; i++){        ret[i] = runningprefix;        runningprefix*= nums[i];    }    int runningsufix = 1;    for(int i = leng -1; i >= 0; i--){        ret[i] *= runningsufix;        runningsufix *= nums[i];    }    return ret;  }

原创粉丝点击