题解 | #乳牛各类产奶统计#【Java】

乳牛各类产奶统计

https://www.nowcoder.com/practice/4e4c1e24208e44a8a9b8c7dd5f829017?tpId=354&tqId=10588090&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj

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 leftProduct = 1;
    for (int i = 0; i < n; i++) {
        others[i] = leftProduct;
        leftProduct *= milk_amount[i];
    }

    // 计算右侧所有元素的乘积,并与左侧乘积相乘
    int rightProduct = 1;
    for (int i = n - 1; i >= 0; i--) {
        others[i] *= rightProduct;
        rightProduct *= milk_amount[i];
    }

    return others;
    }
}

本题知识点分析:

1.数学模拟

2.数组遍历

本题解题思路分析:

1.先计算左侧所有元素的乘积,其实就得到一个准确的105

2.计算右侧所有元素的乘积,并与左侧乘积相乘 就可以得到除自己外的所有数乘积

3.因为题目要求是O(N)所以会比较难想,如果不限时间复杂度还是比较简单的

本题使用编程语言: Java

高频面试算法题解 文章被收录于专栏

高频面试算法题解,每天一小步,人生一大步,跟着一起刷起来!

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务