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

题目描述

给你一个整数数组 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;
}
相关推荐
Jasmine_llq6 分钟前
《P15798 [GESP202603 五级] 有限不循环小数》
算法·有限小数判定数论定理·质因子约分检验·枚举生成合法数字·哈希集合去重·快速 io 优化
学计算机的计算基14 分钟前
操作系统八股文:进程与线程全面梳理(附调度算法+IPC+锁机制)
java·算法
程序猿乐锅1 小时前
【数据结构与算法 | 第二篇】 双链表的增删改查
数据结构
xyy1231 小时前
C# Polly 弹性策略库指南
算法
geovindu2 小时前
go: Recursion Algorithm
开发语言·后端·算法·golang·递归算法
Shadow(⊙o⊙)3 小时前
日志与线程池
linux·c++·算法
冷小鱼3 小时前
AI Agent 的核心算法:多智能体协作(Multi-Agent Systems)
前端·人工智能·算法·multi-agent·多智能体协作·systems
QN1幻化引擎3 小时前
# DalinX V8 灵鉴 V2:12维意识评测框架 —— 从 Tononi IIT 到 Friston FEP 的理论统一
数据库·人工智能·算法·机器学习·数据挖掘·agi
牧以南歌〆3 小时前
数据结构<一>顺序表
c语言·数据结构·算法
Fairy要carry3 小时前
面试-训练显存占用估计
算法