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


题目大意:某一整型数组,对于其中的每个元素,计算数组中除了该元素之外所有元素的积,用数组返回结果。

题目思路:

解法一:先对于每一个元素,计算这个元素左边所有元素的积,再用该乘积乘上该元素右边所有元素的乘积。重点是采取累乘的作法,一共只遍历数组两遍,避免O(n*n)的时间复杂度。代码如下:(2ms,beats 37.78%)

public int[] productExceptSelf(int[] nums) {
        int len = nums.length,rightProduct=1;
		int[] output = new int[len];
		output[0] = 1;
		for (int i = 1; i < len; i++) {
			output[i] = output[i - 1] * nums[i - 1];
		}

		for (int i = len - 1; i >= 0; i--) {
			output[i] *= rightProduct;
			rightProduct *= nums[i];
		}
		return output;
    }

解法二:计算所有元素的乘积 product,则对于每一个元素nums[i], 当nums[i] 不为零时,除该元素外所有元素的乘积output[I]=product/nums[i]。若nums[i] = 0,则所有j != i,output[j] = 0,再遍历一遍数组计算output[i]即可。代码如下:(2ms,beats 37.78%)

public int[] productExceptSelf(int[] nums) {
		int len = nums.length, product = 1;
		int[] output = new int[len];
		for (int num : nums)
			product *= num;
		for (int i = 0; i < len; i++) {
			if (nums[i] == 0) {
				int k = 1;
				for (int j = 0; j < i && k != 0; j++)
					k *= nums[j];
				for (int j = i + 1; j < len && k != 0; j++) {
					k *= nums[j];
					output[j] = 0;
				}
				output[i] = k;
				return output;
			}
			output[i] = product / nums[i];
		}
		return output;
	}


你可能感兴趣的:(LeetCode,算法,数组)