【力扣 - 除自身以外数组的乘积】

题目描述

给你一个整数数组 nums,返回 数组 answer ,其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。

题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。

请 不要使用除法,且在 O(n) 时间复杂度内完成此题。

示例 1:

输入: nums = [1,2,3,4]

输出: [24,12,8,6]

示例 2:

输入: nums = [-1,1,0,-3,3]

输出: [0,0,9,0,0]

提示:

2 <= nums.length <= 10^5
-30 <= nums[i] <= 30

保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。

题解

解题思路

左右乘积表,分别计算i左侧和右侧乘积。

代码

c 复制代码
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

// Function to compute the product of all elements in the input array except the current element
int* productExceptSelf(int* nums, int numsSize, int* returnSize) {
    // Arrays to store the product of elements to the left and right of each element
    int leftProduct[numsSize];
    int rightProduct[numsSize];
    
    // Calculate the product of elements to the left of each element
    leftProduct[0] = 1;
    for (int i = 1; i < numsSize; i++) {
        leftProduct[i] = leftProduct[i - 1] * nums[i - 1];
    }
    
    // Calculate the product of elements to the right of each element
    rightProduct[numsSize - 1] = 1;
    for (int j = numsSize - 2; j >= 0; j--) {
        rightProduct[j] = rightProduct[j + 1] * nums[j + 1];
    }
    
    // Set the return size for the caller
    *returnSize = numsSize;
    
    // Compute the final product array by multiplying left and right products
    int* Answer = (int*)malloc(sizeof(int) * numsSize);
    for (int k = 0; k < numsSize; k++) {
        Answer[k] = leftProduct[k] * rightProduct[k];
    }
    
    return Answer;
}
相关推荐
独自破碎E2 分钟前
【单调队列】滑动窗口的最大值
leetcode
sali-tec6 分钟前
C# 基于OpenCv的视觉工作流-章12-双边滤波
图像处理·人工智能·opencv·算法·计算机视觉
闻缺陷则喜何志丹7 分钟前
P10160 [DTCPC 2024] Ultra|普及+
数据结构·c++··洛谷
wen__xvn9 分钟前
代码随想录算法训练营DAY17第六章 二叉树 part05
数据结构
乌萨奇也要立志学C++10 分钟前
【洛谷】分治专题 逆序对、第 k 小、最大子段和
c++·算法
D_FW11 分钟前
【Java】Redis五大核心数据结构底层原理解析
java·数据结构·redis
sonadorje11 分钟前
逻辑回归的对数损失
算法·机器学习·逻辑回归
燃于AC之乐16 分钟前
我的算法修炼之路--6 ——模幂、构造、背包、贪心、剪枝、堆维护六题精析
c++·数学·算法·贪心算法·dfs·剪枝·01背包
NAGNIP8 小时前
一文搞懂树模型与集成模型
算法·面试
NAGNIP9 小时前
万字长文!一文搞懂监督学习中的分类模型!
算法·面试