【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+" ");
        }
    }
}
相关推荐
Han.miracle1 小时前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
mit6.8243 小时前
前后缀分解
算法
你好,我叫C小白4 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
寂静山林6 小时前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway6 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
Madison-No77 小时前
【C++】探秘vector的底层实现
java·c++·算法
Swift社区7 小时前
LeetCode 401 - 二进制手表
算法·leetcode·ssh
派大星爱吃猫7 小时前
顺序表算法题(LeetCode)
算法·leetcode·职场和发展
liu****7 小时前
8.list的模拟实现
linux·数据结构·c++·算法·list
地平线开发者8 小时前
征程 6 | 征程 6 工具链如何支持 Matmul/Conv 双 int16 输入量化?
算法·自动驾驶