题解 | #牛群重量积#
牛群重量积
https://www.nowcoder.com/practice/d3c6930f140f4b7dbf3a53dd36742193
考察数组的模拟操作。total记录所有数的乘积,除了首尾的两个数之外,其他的数去计算的时候都是用total除以前后以及本身位置的这个数,结果存储在数组中。
完整Java代码如下所示
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型一维数组
*/
public int[] productExceptSelf (int[] nums) {
int total = 1; //所有数的乘积
int[] arr = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
total *= nums[i];
}
for (int i = 0; i < nums.length; i++) {
int pre = 1, last = 1;
if (i>=1) {
pre = nums[i - 1];
}
if (i < nums.length-1) {
last = nums[i + 1];
}
arr[i] = total / (pre * last * nums[i]);
}
return arr;
}
}
查看12道真题和解析