238_Product of Array Except Self

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

给定一个数组,返回一个和它大小相同的数组,且对应位置的值为原数组除该位置所有元素的乘积。

思路:

首先,通过原数组顺序遍历得到一个数组,这个数组中每个元素的值为该位置以前所有元素的成绩,第一个值由于前面没有任何值可以做乘积,赋为0

然后,反向遍历该数组,每个位置的结果为:该位置之前所有元素的乘积 * 该位置之后所有元素的乘积。

    其中,该位置之后所有元素的乘积用remind表示,由于是从后向前遍历,最后一个元素(值为之前所有元素乘积)已经为要得到结果,初始化remind=1,然后每向前一步,在第j个位置,在计算过结果之后要remind*=nums[j](若在计算最终结果之前计算remind,则需要remind*=nums[j-1])来保证remind像前走时每个位置都为该位置向后所有元素乘积。

  最后,第一个元素returnNums[0]需要手动将remind赋值进去,因为remind为第一个元素向后所有元素乘积,即为该位置的结果。

public class Solution {
    public int[] ProductExceptSelf(int[] nums) {
        
        int[] returnNums = new int[nums.Count()];
        
        if(nums.Count() > 0)
        {
            int remind = 1;
            returnNums[0] = 1;
            
            for(int i = 1; i < returnNums.Count(); i++)
            {
                returnNums[i] = returnNums[i - 1] * nums[i - 1];
            }
            
            for(int j = returnNums.Count() - 1; j > 0; j--)
            {
                returnNums[j] = returnNums[j] * remind;
                remind *= nums[j];
            }
            
            returnNums[0] = remind;
        }
        return returnNums;
    }
}
原文地址:https://www.cnblogs.com/Anthony-Wang/p/5069642.html