LeetCode238. Product of Array Except Self

博客围绕给定数组,要求返回一个数组,其元素为原数组除自身外所有元素的乘积。解题难点在于处理0元素,分无0元素、1个0元素、2个及以上0元素三种情况讨论,并给出了相应思路,还提及不使用除法且时间复杂度为O(n)等要求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array nums of n integers where n > 1,  return an array output such that output[i]is equal to the product of all the elements of nums except nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

思路:

这道题我开始以为会有非常大的数出现作为一个难点,但是并没有;这道题的难点在于解决0元素的问题,我们这里分三种情况讨论:

1 没有0元素,这个时候我们只需要按照常规的用累乘除以目标数就可以了

2 有1一个0元素,这个时候除了0元素的位置,其他的数应该都是0

3 有2个及以上的0元素,这个时候所有位置的元素最后都会变成0

代码如下:

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
		int product = 1;
		int zeroCount = 0;
		for (int num : nums) {
			if (num == 0) zeroCount++;
			else product *= num;
		}
		if (zeroCount > 1) return vector<int>(nums.size(), 0);

		if (zeroCount > 0) {
			for (int& num : nums) {
				if (num == 0) num = product;
				else num = 0;
			}
		}
		else {
			for (int& num : nums) num = product / num;
		}
		return nums;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值