题解 | #乳牛各类产奶统计#
乳牛各类产奶统计
https://www.nowcoder.com/practice/4e4c1e24208e44a8a9b8c7dd5f829017
考察的知识点:数组;
解答方法分析:
- 创建一个大小为 n 的数组 others,并用 1 初始化。
- 进行第一次遍历。从左到右遍历数组 milk_amount,对于每个元素 milk_amount[i],将其左侧所有元素的乘积累积到 others[i] 上。具体操作是:先将 left 初始化为 1,然后对于每个元素 milk_amount[i],将 left 乘以 milk_amount[i],再将乘积赋值给 others[i],最后更新 left 为乘积。
- 进行第二次遍历。从右到左遍历数组 milk_amount,对于每个元素 milk_amount[i],将其右侧所有元素的乘积累积到 others[i] 上。具体操作是:先将 right 初始化为 1,然后对于每个元素 milk_amount[i],将 right 乘以 milk_amount[i],再将乘积赋值给 others[i],最后更新 right 为乘积。
- 返回数组 others。
所用编程语言:C++;
完整编程代码:↓
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param milk_amount int整型vector * @return int整型vector */ vector<int> product_except_self(vector<int>& milk_amount) { int n = milk_amount.size(); vector<int> others(n, 1); int left = 1; for (int i = 0; i < n; i++) { others[i] *= left; left *= milk_amount[i]; } int right = 1; for (int i = n - 1; i >= 0; i--) { others[i] *= right; right *= milk_amount[i]; } return others; } };