题解 | #乳牛各类产奶统计# java
乳牛各类产奶统计
https://www.nowcoder.com/practice/4e4c1e24208e44a8a9b8c7dd5f829017
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param milk_amount int整型一维数组 * @return int整型一维数组 */ public int[] product_except_self (int[] milk_amount) { // write code here int n = milk_amount.length; int[] left = new int[n]; int[] right = new int[n]; int[] others = new int[n]; // 计算每个元素左侧所有元素的乘积 int product = 1; for (int i = 0; i < n; i++) { left[i] = product; product *= milk_amount[i]; } // 计算每个元素右侧所有元素的乘积 product = 1; for (int i = n - 1; i >= 0; i--) { right[i] = product; product *= milk_amount[i]; } // 计算其他元素的乘积 for (int i = 0; i < n; i++) { others[i] = left[i] * right[i]; } return others; } }
编程语言是Java。
该题考察的知识点是数组操作和前缀乘积。
代码的文字解释如下:
- 一整型数组left用于存储每个元素左侧所有元素的乘积。
- right用于存储每个元素右侧所有元素的乘积。
- others用于存储除当前元素以外的所有元素的乘积。
- 从左到右遍历原始数组milk_amount,计算left数组的值:初始时将product设为1,然后将product乘以当前元素,并将结果存入left数组对应位置。
- 从右到左遍历原始数组milk_amount,计算right数组的值:初始时将product设为1,然后将product乘以当前元素,并将结果存入right数组对应位置。
- 使用for循环遍历原始数组milk_amount,计算others数组的值:将left数组对应位置的值乘以right数组对应位置的值,并将结果存入others数组对应位置。
- 循环结束后,返回others数组作为最终的结果。