【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+" ");
        }
    }
}
相关推荐
ChillJavaGuy15 小时前
常见限流算法详解与对比
java·算法·限流算法
sali-tec16 小时前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#
你怎么知道我是队长17 小时前
C语言---循环结构
c语言·开发语言·算法
艾醒17 小时前
大模型面试题剖析:RAG中的文本分割策略
人工智能·算法
纪元A梦19 小时前
贪心算法应用:K-Means++初始化详解
算法·贪心算法·kmeans
_不会dp不改名_19 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表
mark-puls19 小时前
C语言打印爱心
c语言·开发语言·算法
Python技术极客19 小时前
将 Python 应用打包成 exe 软件,仅需一行代码搞定!
算法
吃着火锅x唱着歌20 小时前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun20 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划