LeetCode 238: Product of Array Except Self

Given an array of n integers where n > 1, nums, return an arrayoutput 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.)

分析:

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);elseresult.push_back(product/nums[i]);}else{if (zerocount==1)result.push_back(product);elseresult.push_back(0);}}return result;}};

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

每个人的生命都是可以绽放美丽,只要你珍惜。

LeetCode 238: Product of Array Except Self

相关文章:

你感兴趣的文章:

标签云: