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.
examples.
Input: nums = [1,2,3,4] Output: [24,12,8,6]
ํ์ด ๐
์ฒ์์ ์ด์ค ํฌ๋ฌธ์ ์ฌ์ฉํด์ i != j์ธ ๊ฒฝ์ฐ์๋ง ๊ณฑํด์ ๋ฐฐ์ด์ ์ฝ์ ํด์ฃผ์๋ค.
ํ์ง๋ง ์๊ฐ ์ด๊ณผ ๋ฐ์!!
๋ฐ๋ผ์ ๋ชจ๋ ์๋ฅผ ๋ชจ๋ ๊ณฑํ ๋ค์, 0์ ๊ฐ์์ ๋ฐ๋ผ์ ๊ตฌ๋ถํ๋ ๋ฐฉ์์ ์ทจํ๋ค.
์ฆ, ๋จผ์ nums๋ฅผ ์ํํ๋ฉด์ ๋ชจ๋ ๊ฐ์ ๋ค ๊ณฑํด๋๋ค. (product)
๋์ 0์ธ ๊ฒฝ์ฐ์๋ ๊ณฑํ์ง ์๊ณ zeroCount๋ฅผ ํ๋ ์ฌ๋ ค์ค๋ค.
๋ง์ฝ zeroCount > 1์ธ ๊ฒฝ์ฐ์๋ ์๊ธฐ ์์ ์ ์ ์ธํ๋๋ผ๋ 0์ด ๋ฌด์กฐ๊ฑด ์กด์ฌํ๋ค๋ ์๋ฏธ์ด๊ธฐ์ ๋ชจ๋ 0์ธ ๋ฐฐ์ด์ ๋ฐํํ๋ค.
๊ทธ๋ ์ง ์์ ๊ฒฝ์ฐ์๋ ๋ค์ nums๋ฅผ ์ํํ๋ฉด์, zeroCount == 1์ธ ๊ฒฝ์ฐ์๋ ๋ด๊ฐ 0์ธ์ง, ๋จ์ด 0์ธ์ง ํ๋จํ์ฌ ๊ณ์ฐํ๋ค.
์์ค์ฝ๋ ๐ฉ๐ป๐ป
class Solution {
public int[] productExceptSelf(int[] nums) {
int zeros = 0;
int product = 1;
int[] answer = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
zeros++;
continue;
}
product *= nums[i];
}
if (zeros > 1) {
return answer;
}
for (int i = 0; i < nums.length; i++) {
if (zeros == 1 && nums[i] == 0) {
answer[i] = product;
} else if (zeros == 1 && nums[i] != 0) {
answer[i] = 0;
} else {
answer[i] = product / nums[i];
}
}
return answer;
}
}