💬 Info
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.
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
answer[i]
is guaranteed to fit in a 32-bit integer.풀이 시간 : 40분
result[i]
에 왼쪽 곱셈 결과 저장result[i]
에 곱해 최종값 출력class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] result = new int[n];
result[0] = 1;
for (int i = 1; i < n; i++) {
result[i] = result[i - 1] * nums[i - 1];
}
int right = 1;
for (int i = n - 1; i >= 0; i--) {
result[i] *= right;
right *= nums[i];
}
return result;
}
}