码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 238: Product of Array Except Self

时间:2015-07-27 21:10:30      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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、如果数组中有两个及以上的0,那么结果数组的每一项都为0.

2、如果数组中只有一个0,那么结果数组中,0对应的位置,为数组中其他元素的成绩,其余位置都为0。

3、如果数组中没有0,那么结果数组每一项均为数组所有元素的乘积/当前数组元素。


需要扫描数组两次,算法时间复杂度为O(n):

第一次:计算0的个数,以及非0元素的乘积。

第二次,计算结果数组每一位的元素。


需要两个临时变量: product保存非0元素的乘积,zeroCount计算0元素的个数,空间复杂度为O(1)。

代码如下:

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
      long int product = 1;
		vector<int> result;
		int length = nums.size();
		int zerocount = 0;
		for (int i=0; i<length; i++)
		{
			if (nums[i] !=  0)
			{
				product *= nums[i];
			}else{
				zerocount++;
			}
			
		}
		for (int i=0; i<length; i++)
		{
			if (nums[i] != 0 )
			{
				if (zerocount != 0)
					result.push_back(0);
				else
					result.push_back(product/nums[i]);
			}else{
				if (zerocount==1)
					result.push_back(product);
				else
					result.push_back(0);
				
			}
		}
		return result;
	}

};



版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode 238: Product of Array Except Self

标签:leetcode

原文地址:http://blog.csdn.net/sunao2002002/article/details/47089053

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!