【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+" ");
        }
    }
}
相关推荐
lifallen10 分钟前
Hadoop MapReduce 任务/输入数据 分片 InputSplit 解析
大数据·数据结构·hadoop·分布式·算法
熙xi.1 小时前
数据结构 -- 哈希表和内核链表
数据结构·算法·散列表
Ghost-Face1 小时前
并查集提高——种类并查集(反集)
算法
董董灿是个攻城狮2 小时前
5分钟搞懂大模型微调的原始能力退化问题
算法
艾醒6 小时前
大模型面试题剖析:大模型微调与训练硬件成本计算
人工智能·后端·算法
啊嘞嘞?6 小时前
力扣(滑动窗口最大值)
算法·leetcode·职场和发展
快递鸟6 小时前
ISV系统开发中物流接口的第三方模块对接:技术选型与集成实践
算法
墨染点香6 小时前
LeetCode 刷题【53. 最大子数组和】
数据结构·算法·leetcode
2501_924879267 小时前
客流特征识别误报率↓76%!陌讯多模态时序融合算法在智慧零售的实战解析
大数据·人工智能·算法·目标检测·计算机视觉·视觉检测·零售
北京地铁1号线7 小时前
广告推荐模型2:因子分解机(Factorization Machines, FM)
人工智能·算法·推荐算法