力扣:除自身以外数组的乘积

  1. 思路分析 :
    • 对每个 nums[i],计算其左边所有元素的乘积和右边所有元素的乘积,然后将这两个乘积相乘,就得到了除 nums[i] 之外其余各元素的乘积。
    • 例如对于数组 [a, b, c, d],计算 nums[1](即 b)的结果时,左边元素乘积为 a,右边元素乘积为 c * d,那么结果就是 a * c * d。
  2. 算法思路 :
    • 初始化:创建数组LProduct和RProduct。
    • 计算左边乘积 :
      • 左乘积数组 lProducti:存储索引 i 左边所有元素的乘积。
    • 计算右边乘积并合并结果 :
      • 右乘积数组 rProducti:存储索引 i 右边所有元素的乘积。
    • 结果数组 :
      • 结果数组 resi = lProducti * rProducti。
  3. 代码实现:
java 复制代码
package main.leetcode75.arr_str;

import java.util.Arrays;

/**
 * @ClassName ProductExceptSelf
 * @Description
 * @Author Feng
 * @Date 2025/12/29
 **/
public class ProductExceptSelf {
    public int[] productExceptSelf(int[] nums) {
        int[] res = new int[nums.length];
        int[] lProduct = new int[nums.length];
        int[] rProduct = new int[nums.length];

        // 初始化lproduct数组的值
        lProduct[0] = 1;
        for (int i = 1; i < nums.length; i++) {
            lProduct[i] = nums[i - 1] * lProduct[i - 1];
        }

        rProduct[rProduct.length-1] = 1;
        for (int i = rProduct.length-2; i >= 0 ; i--) {
            rProduct[i] = nums[i+1] * rProduct[i+1];
        }

        for (int i = 0; i < nums.length; i++) {
            res[i] = lProduct[i] * rProduct[i];
        }

        return res;
    }

    public static void main(String[] args) {
        ProductExceptSelf productExceptSelf = new ProductExceptSelf();
        int[] nums = {1, 2, 3, 4};
        int[] result = productExceptSelf.productExceptSelf(nums);
        Arrays.stream(result).forEach(System.out::println);
    }
}
  1. 复杂度分析 :
    • 时间复杂度:O(n) - 三次遍历数组。
    • 空间复杂度:O(n) - 使用了两个额外数组。
相关推荐
Percep_gan36 分钟前
调用天翼云的对象存储ZOS,很详细
java·1024程序员节
Navigator_Z38 分钟前
LeetCode //C - 1300. Sum of Mutated Array Closest to Target
c语言·算法·leetcode
SZYSK40 分钟前
鸿蒙人脸识别算法放在终端里:和外挂授权 SDK 差在排障路径
物联网·算法·华为·harmonyos
若亦_1 小时前
数据结构>>优先级队列(堆)
java·数据结构
Wang's Blog1 小时前
Java 项目实战: 交友项目 - 查询圈子个人动态:查询我的动态需求分析
java·开发语言·交友
denlaku1 小时前
JDK 23 新特性详解
java
凯瑟琳.奥古斯特1 小时前
力扣1016高效解法:剪枝优化技巧
开发语言·c++·算法·leetcode·职场和发展
code2cat1 小时前
Java高级篇之Hibernate:让对象映射到表,理解持久化与事务
java·后端·hibernate·1024程序员节
xiangyun612 小时前
C++ priority_queue 底层:手撕二叉堆与 Top K 问题
c++·算法·面试·stl·1024程序员节
骑着蜗牛撵大象3272 小时前
飞牛fnOS部署Damselfly:Compose编排、照片目录与7100固定访问
java·docker·rpc·dubbo·fnos·照片管理·damselfly