本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/48598939
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.)
思路:
(1)题意为给定一个整形数组,要求输出的结果数组相对于原数组位置的值为原数组中除去该位置的其它值的乘积。例如,对个给定的数组[1,3,5],则结果数组第1个位置上的值为3*5=15,第二个位置上的值为1*5=5;第三个位置上的值为1*3=3。
(2)该题不是很难,需要注意的是0的个数。首先,判断数组中0的个数,并设置变量sum和sum0分别保存数组中所有元素的乘积和数组中除去0的乘积;其次,如果0的个数大于等于2,则说明原数组中去掉任意元素后剩余元素的乘积都为0,所以目标数组中元素的值全为0;如果sum的值为0,则说明原数组中只有一个元素为0,则在遍历的过程中,只需将遇到遇到0的元素对应的值设置为sum0,其余元素都设为0;如果sum的值不为0,则说明原数组中没有为0的元素,此时,只需将sum除以当前遍历元素的值即为目标数组当前位置的值。
(3)详情见下方代码。希望本文对你有所帮助。
算法代码实现如下:
package leetcode;
/**
*
* @author liqqc
*
*/
public class Product_of_Array_Except_Self {
public int[] productExceptSelf(int[] nums) {
if (nums == null || nums.length == 0)
return null;
int sum = 1;
int sum0 = 1;
int zorecut = 0;
for (int i : nums) {
if (i == 0) {
zorecut++;
}
if (i != 0) {
sum0 = sum0 * i;
}
sum = sum * i;
}
if (zorecut >= 2) {
for (int i = 0; i < nums.length; i++) {
nums[i] = 0;
}
return nums;
}
if (sum == 0) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[i] = 0;
} else {
nums[i] = sum0;
}
}
return nums;
} else {
for (int i = 0; i < nums.length; i++) {
nums[i] = sum / nums[i];
}
return nums;
}
}
}