leetCode-Product of Array Except Self

来源:互联网 发布:apache base64 maven 编辑:程序博客网 时间:2024/06/06 02:35

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

My Solution:

class Solution {//主要思想就是求出所有数的乘积,遍历数组,除以nums[i]就可以了,只不过有两种特殊情况,一种是数组中有一个元素为0,那么可以将其他元素赋为0,0元素为其他元素乘积,如果数组中为0的元素多于1,那么直接返回0数组    public int[] productExceptSelf(int[] nums) {        int len = nums.length;        int[] result = new int[len];        int m = 1;        int zeroCount = 0;        int index = 0;        for(int i = 0;i < len;i++){            if(nums[i] != 0){                m *= nums[i];            }else{                zeroCount++;                index = i;            }        }        if(zeroCount != 0){            if(zeroCount == 1){                 for(int i = 0;i < len;i++){                 if(i == index){                     result[i] = m;                  }else{                     result[i] = 0;                 }             }            }            return result;        }        for(int i = 0;i < len;i++){            result[i] = m / nums[i];        }        return result;    }}

Better Solution:

//第一遍遍历,product[i]对应i之前的所有元素乘积,第二遍逆序遍历,product[i]补上之前缺少的部分class Solution {    public int[] productExceptSelf(int[] nums) {        int[] products = new int[nums.length];        int num = 1;        for (int i = 0; i < nums.length; i++) {            products[i] = num;            num *= nums[i];        }        num = 1;        for (int i = nums.length - 1; i >= 0; i--) {            products[i] *= num;            num *= nums[i];        }        return products;    }}