题解 | 牛群重量积

牛群重量积

https://www.nowcoder.com/practice/d3c6930f140f4b7dbf3a53dd36742193

import java.util.*;


public class Solution {
    public int[] productExceptSelf (int[] nums) {
        // 2   3   4   5   6
        // 2   6  24  120 720
        //720 360 120  30   6 
        //120 30  12   6  24
        final int n = nums.length;
        final int[] prefixProduct = new int[n], suffixProduct = new int[n];
        prefixProduct[0] = nums[0];
        suffixProduct[n - 1] = nums[n - 1];
        for (int i = 1; i < n; ++i) {
            prefixProduct[i] = prefixProduct[i - 1] * nums[i];
            suffixProduct[n - 1 - i] = suffixProduct[n - i] * nums[n - 1 - i];
        }
        int[] ans = new int[n];
        for (int i = 0; i < n; ++i) {
            ans[i] = 1;
            ans[i] *= i - 2 >= 0 ? prefixProduct[i - 2] : 1; 
            ans[i] *= i + 2 < n ? suffixProduct[i + 2] : 1; 
        }
        return ans;
    }
}

全部评论

相关推荐

我要娶个什么名:学长你电脑闹鬼了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务