【Hot100】LeetCode—238. 除自身以外数组的乘积

目录

  • [1- 思路](#1- 思路)
  • [2- 实现](#2- 实现)
    • [⭐238. 除自身以外数组的乘积------题解思路](#⭐238. 除自身以外数组的乘积——题解思路)
  • [3- ACM 实现](#3- ACM 实现)


1- 思路

前缀和

  • 1- 维护 左乘积前缀和 preL 和 右乘积前缀和 preR

    • 左前缀和乘积:从 1 开始遍历,到 nums.length
    • 右前缀和乘积:从 nums.length-1 开始遍历,到 0
    1. 遍历结果数组
    • res[i] = preL[i] * preR[i]

2- 实现

⭐238. 除自身以外数组的乘积------题解思路

java 复制代码
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] res = new int[nums.length];
        int[] preL = new int[nums.length];
        int[] preR = new int[nums.length];

        preL[0] = 1;
        preR[nums.length-1] = 1;

        for(int i = 1 ; i < nums.length;i++){
            preL[i] = preL[i-1] *nums[i-1];
        }

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

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

        return res;
    }
}

3- ACM 实现

java 复制代码
public class productExceptSelf {

    public static int[] product(int[] nums){
        int[] res = new int[nums.length];
        int[] preL = new int[nums.length];
        int[] preR = new int[nums.length];

        // 求左前缀
        preL[0] = 1;
        for(int i = 1;i<nums.length;i++){
            preL[i] = preL[i-1]*nums[i-1];
        }

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

        for(int i = 0 ;i < nums.length;i++){
            res[i] = preL[i]*preR[i];
        }
        return res;
    }


    public static void main(String[] args) {
        System.out.println("输入数组长度");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] nums = new int[n];
        for(int i = 0 ; i < n;i++){
            nums[i] = sc.nextInt();
        }
        int[] res = product(nums);
        for(int i : res){
            System.out.print(i+" ");
        }
    }
}
相关推荐
ysh98884 分钟前
PP-OCR:一款实用的超轻量级OCR系统
算法
遇雪长安20 分钟前
差分定位技术:原理、分类与应用场景
算法·分类·数据挖掘·rtk·差分定位
数通Dinner24 分钟前
RSTP 拓扑收敛机制
网络·网络协议·tcp/ip·算法·信息与通信
张人玉2 小时前
C# 常量与变量
java·算法·c#
weixin_446122463 小时前
LinkedList剖析
算法
百年孤独_4 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表
我爱C编程4 小时前
基于拓扑结构检测的LDPC稀疏校验矩阵高阶环检测算法matlab仿真
算法·matlab·矩阵·ldpc·环检测
算法_小学生5 小时前
LeetCode 75. 颜色分类(荷兰国旗问题)
算法·leetcode·职场和发展
运器1235 小时前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程
算法_小学生5 小时前
LeetCode 287. 寻找重复数(不修改数组 + O(1) 空间)
数据结构·算法·leetcode