Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
class Solution {
public int[] productExceptSelf(int[] nums) {
int zeroIdx = -1;
int total = 1;
int[] result = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
if (num == 0) {
if (zeroIdx != -1) {
return result;
}
zeroIdx = i;
continue;
}
total *= num;
}
if (zeroIdx != -1) {
result[zeroIdx] = total;
return result;
}
for (int i = 0; i < nums.length; i++) {
result[i] = total / nums[i];
}
return result;
}
}
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int ans[] = new int[n];
for(int i = 0; i < n; i++) {
int pro = 1;
for(int j = 0; j < n; j++) {
if(i == j) continue;
pro *= nums[j];
}
ans[i] = pro;
}
return ans;
}
}
브루트포스로도 풀린다