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

  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) - 使用了两个额外数组。
相关推荐
小张成长计划..15 分钟前
【Linux】44:五种IO模型与非阻塞IO
java·服务器·数据库
不甘平凡的小鸟23 分钟前
vs code 打开spring boot项目
java·spring boot·后端
ZhengEnCi24 分钟前
Java 内存泄漏怎么排查:jstat、heap dump 与 MAT 线上定位流程
java·jvm·性能优化
Shaoshing1 小时前
LeetCode 921.使括号括号有效的最少添加
java·算法·leetcode·职场和发展
xurileidian2 小时前
第 30 篇 · 边玩边学Python · 猜数字小游戏 把判断循环异常串起来
前端·python·算法
电科_银尘2 小时前
【大模型算法与工程 65】小数据VLM微调:图文格式、任务与损失
深度学习·算法·机器学习
远航计算机2 小时前
豆包GEO算法实证:引用池到答案之间,还有8.3%入选与13%失配两道关
人工智能·深度学习·算法
赤生云电竞2 小时前
云电竞GPU虚拟化选型:vGPU与直通架构实践对比
java·开发语言·架构
Ryan-Zhong2 小时前
视频解析 API 拒绝解析怎么判定:reason 分流与门禁
java·数据库·音视频
吹什么轩2 小时前
c++高并发内存池(一):从objectpool到central cache
java·开发语言