【发布时间】:2021-10-04 19:36:06
【问题描述】:
我一直在 leetcode 上尝试这个问题。 238.Product of array except self
给定一个整数数组nums,返回一个数组答案,使得 answer[i] 等于 nums 的所有元素的乘积,除了 nums[i].
nums 的任何前缀或后缀的乘积都保证适合 32 位整数。
您必须编写一个在 O(n) 时间内运行且不使用 除法运算。
示例 1:
Input: nums = [1,2,3,4] Output: [24,12,8,6]示例 2:
Input: nums = [-1,1,0,-3,3] Output: [0,0,9,0,0]
这是我对上述问题的解决方案。
public int[] productExceptSelf(int[] nums) {
int answer[]=new int[nums.length];
for(int i=0;i<nums.length;i++){
int prod=1;
for(int j=0;j<nums.length;j++){
if(j!=i)
prod=prod*nums[j];
}
answer[i]=prod;
}
return answer;
}
这是通过 19/20 测试用例。有一个测试用例不起作用,我收到错误“超出时间限制。”
失败的测试用例如下:
Input: [-1,-1,-1,-1,..............]; Output: Time limit exceeded.
如果有人可以帮助我对我的代码做哪个版本?
【问题讨论】:
标签: java arrays prefix-sum