题解 | #乳牛各类产奶统计#
乳牛各类产奶统计
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[] others = new int[n]; int[] leftProducts = new int[n]; leftProducts[0] = 1; for(int i=1;i<n;i++){ leftProducts[i] = leftProducts[i-1]*milk_amount[i-1]; } int rightProducts =1; for(int i=n-1;i>=0;i--){ others[i] = leftProducts[i]*rightProducts; rightProducts *= milk_amount[i]; } return others; } }
首先创建一个数组 leftProduct
来存储每个元素左边的乘积,然后计算右边的乘积,并将左边的乘积与右边的乘积相乘,得到 others
数组,即其他品种的牛产奶量的乘积。最后返回 others
数组作为结果。