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

题目描述

给你一个整数数组 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;
}
相关推荐
纪念 2299 分钟前
C++算法(六)
开发语言·c++·算法
Dumbness1 小时前
UIA 读微信群消息没有 id,怎么判断哪条是新的:后缀对齐在翻历史和撤回时整屏重报
python·算法
taka1 小时前
从 24x 到 141x:我用纯 Python 零依赖项目,扒开了 GPU 加速的性能黑洞
算法
UIU1142 小时前
P16237 [蓝桥杯 2026 省 B] 应急布线
数据结构·c++·算法·蓝桥杯
旖旎夜光2 小时前
LeetCode 315: 算右侧小于当前元素的个数(归并排序) —— 题解
c++·学习·算法·leetcode·排序算法
像风一样自由20202 小时前
2.如何用FastAPI把一个Python算法封装成HTTP服务
python·算法·fastapi
D e re k ZH2 小时前
保序回归:从 PAVA 到可并堆的单调约束优化
c++·算法·数据挖掘·回归·kotlin
青少儿编程课堂2 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:字典树前缀树与单词检索统计
c++·python·算法·bfs·信息学竞赛
文丑颜不良啊2 小时前
LeetCode1401~1420题目解析
java·leetcode
Nuanyt2 小时前
LeetCode Hot 100 链表专题2 3 题 (Java)
java·笔记·算法·leetcode·链表