Leetcode_238_Product of Array Except Self

97 篇文章 0 订阅
94 篇文章 18 订阅

本文是在学习中的总结,欢迎转载但请注明出处: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;
		}

	}

}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值