238. Product of Array Except Self

来源:互联网 发布:化妆品采购数据分析 编辑:程序博客网 时间:2024/06/06 12:49

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

这道题最初解决的时候我的想法是统计数组中0的个数,思想很简单,也容易理解,直接上代码,代码如下:

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] result = new int[nums.length];
        int count = 0;
        for(int i = 0; i < nums.length; i++){
            if(nums[i] == 0){
                count++;
            }
        }
        
        if(count > 1){
            for(int i = 0; i < nums.length; i++){
                result[i] = 0;
            }
            return result;
        }else if(count == 1){
            int temp = 1;
            for(int i = 0; i < nums.length; i++){
                if(nums[i] != 0){
                    temp *= nums[i];
                }
            }
            
            for(int i = 0; i < nums.length; i++){
                if(nums[i] == 0){
                    result[i] = temp;
                }else{
                    result[i] = 0;
                }
            }
            
            return result;
        }else{
            int temp = 1;
            for(int i = 0; i < nums.length; i++){
                temp *= nums[i];
            }
            for(int i = 0; i < nums.length; i++){
                result[i] = temp / nums[i];
            }
            return result;
        }
    }
}

但是这样写不够美观整洁,时间复杂度与空间复杂度都是最优的,但是代码太多让人不舒服,后来找到一种更好的方法,代码如下:

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] result = new int[nums.length];
        for(int i = 0; i < result.length; i++){
            result[i] = 1;
        }
        int start = 1;
        for(int i = 0; i < nums.length; i++){
            result[i] *= start;
            start = start * nums[i];
        }
        
        int end = 1;
        for(int i = nums.length - 1; i >= 0; i--){
            result[i] *= end;
            end = end * nums[i];
        }
        
        return result;
    }
}这样看起来就比较简洁,解决问题的办法不止一种,我们要根据情况选择最适合的方法。


0 0
原创粉丝点击