题解 | 牛群重量积
牛群重量积
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;
}
}
查看8道真题和解析