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

题目描述

给你一个整数数组 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;
}
相关推荐
月落归舟7 分钟前
帮你从算法的角度来认识二叉树---(二)
算法·二叉树
清华都得不到的好学生1 小时前
数据结构->1.稀疏数组,2.数组队列(没有取模),3.环形队列
java·开发语言·数据结构
SilentSlot1 小时前
【数据结构】Hash
数据结构·算法·哈希算法
是娇娇公主~2 小时前
Lambda表达式详解
数据结构·c++
样例过了就是过了2 小时前
LeetCode热题100 柱状图中最大的矩形
数据结构·c++·算法·leetcode
wsoz2 小时前
Leetcode哈希-day1
算法·leetcode·哈希算法
阿Y加油吧2 小时前
LeetCode 二叉搜索树双神题通关!有序数组转平衡 BST + 验证 BST,小白递归一把梭
java·算法·leetcode
BlockChain8882 小时前
区块链的组件:从数据结构到去中心化共识
数据结构·去中心化·区块链
liuyao_xianhui3 小时前
优选算法_最小基因变化_bfs_C++
java·开发语言·数据结构·c++·算法·哈希算法·宽度优先
jimy13 小时前
C语言实现-----面向对象编程
c语言·数据结构