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

题目描述

给你一个整数数组 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;
}
相关推荐
YXXY3131 小时前
模拟算法的介绍
算法
happymaker06262 小时前
简单LRU的实现(基于LinkedHashMap)
算法·leetcode·lru
会编程的土豆2 小时前
【数据结构与算法】空间复杂度从入门到面试:不仅会算,还要会解释
数据结构·c++·算法·面试·职场和发展
普通网友2 小时前
《算法面试必刷:15 个高频 LeetCode 题(附代码)》
算法·leetcode·面试
_深海凉_2 小时前
LeetCode热题100-搜索二维矩阵
算法·leetcode·矩阵
张槊哲2 小时前
C++ 进阶指南:如何丝滑地理解与实践多线程与多进程
开发语言·c++·算法
代码中介商3 小时前
C语言链表完全指南:从单节点到链表管理
c语言·算法·链表
小小de风呀3 小时前
de风——【从零开始学C++】(四):类和对象(下)
开发语言·c++·算法
aqiu1111114 小时前
[特殊字符]【算法日记 14】数论入门神题:最大公约数与最小公倍数的“乘积守恒定律”
算法
保卫大狮兄4 小时前
一文讲清:仓库管理最核心的10个公式
人工智能·算法·仓库管理