← 中文资源

简体中文版本

前缀后缀两遍求除自身外的乘积

先一遍扫描得到每个位置左侧的乘积前缀,再从右往左把后缀乘积折进结果数组:任何位置都不用除法也不会重复相乘,两次线性遍历即可完成。

阅读英文原文

实现说明

函数 product_except_self、main汇总全部行为。 for i in 1..n 承担全部的逐项处理。

使用要点

  • main 的演示流程是 product_except_self——跑一遍文件,这条流程从头到尾可见。

常见问题

「前缀后缀两遍求除自身外的乘积」这个示例怎么运行?

把它当完整程序编译/解释运行即可——不需要先安装任何东西。

签名一览:fn product_except_self(nums: &[i32]) -> Vec<i32>

核心语句

prefix[i] = prefix[i - 1] * nums[i - 1];

代码示例

fn product_except_self(nums: &[i32]) -> Vec<i32> {
    let n = nums.len();
    // prefix[i] = product of everything left of i
    let mut prefix = vec![1; n];
    for i in 1..n {
        prefix[i] = prefix[i - 1] * nums[i - 1];
    }
    // sweep from the right, folding the suffix product into the result
    let mut suffix = 1;
    let mut out = prefix;
    for i in (0..n).rev() {
        out[i] *= suffix;
        suffix *= nums[i];
    }
    out
}

fn main() {
    println!("{:?}", product_except_self(&[1, 2, 3, 4]));
    println!("{:?}", product_except_self(&[2, 3, 0, 5]));
    println!("{:?}", product_except_self(&[5]));
}