【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+" ");
        }
    }
}
相关推荐
Navigator_Z4 分钟前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode
WBluuue6 分钟前
数据结构与算法:莫队(一):普通莫队与带修莫队
c++·算法
风筝在晴天搁浅1 小时前
n个六面的骰子,扔一次之后和为k的概率是多少?
算法
MATLAB代码顾问2 小时前
Python实现蜂群算法优化TSP问题
开发语言·python·算法
代码飞天2 小时前
机器学习算法和函数整理——助力快速查阅
人工智能·算法·机器学习
jiushiapwojdap2 小时前
LU分解法求解线性方程组Matlab实现
数据结构·其他·算法·matlab
笨笨饿3 小时前
69_如何给自己手搓一个串口
linux·c语言·网络·单片机·嵌入式硬件·算法·个人开发
纽扣6673 小时前
【算法进阶之路】链表进阶:删除、合并、回文与排序全解析
数据结构·算法·链表
消失的旧时光-19433 小时前
统一并发模型:线程、Reactor、协程本质是一件事(从线程到协程 · 第6篇·终章)
java·python·算法
智者知已应修善业4 小时前
【51单片机不用数组动态数码管显示字符和LED流水灯】2023-10-3
c++·经验分享·笔记·算法·51单片机