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

题目描述

给你一个整数数组 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;
}
相关推荐
郝学胜-神的一滴几秒前
OpenGL中的glDrawArrays函数详解:从基础到实践
开发语言·c++·程序人生·算法·游戏程序·图形渲染
_OP_CHEN1 分钟前
【算法基础篇】(三十四)图论基础深度解析:从概念到代码,玩转图的存储与遍历
算法·蓝桥杯·图论·dfs·bfs·算法竞赛·acm/icpc
Lv11770089 分钟前
Visual Studio 中的 ArrayList数组 和 List数组
数据结构·笔记·c#·list·visual studio
王璐WL9 分钟前
【数据结构】栈和队列及相关算法题
数据结构·算法
麒qiqi9 分钟前
Linux 线程(POSIX)核心教程
linux·算法
Zhi.C.Yue11 分钟前
React 的桶算法详解
前端·算法·react.js
小热茶14 分钟前
浮点数计算专题【五、 IEEE 754 浮点乘法算法详解---基于RISCV的FP32乘法指令在五级流水线的运行分析与SystemC实现】
人工智能·嵌入式硬件·算法·systemc
Giser探索家14 分钟前
卫星遥感数据核心参数解析:空间分辨率与时间分辨率
大数据·图像处理·人工智能·深度学习·算法·计算机视觉
q_302381955622 分钟前
破局路侧感知困境:毫米波雷达+相机融合算法如何重塑智能交通
数码相机·算法
Robert--cao23 分钟前
人机交互(如 VR 手柄追踪、光标移动、手势识别)的滤波算法
人工智能·算法·人机交互·vr·滤波器