Difficulty: MEDIUM
Categories: ๋ฐฐ์ด/๋ฌธ์์ด
Source: https://leetcode.com/problems/product-of-array-except-self/
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] answer = new int[n];
answer[0] = 1;
for (int i = 1; i < n; i++) {
answer[i] = answer[i - 1] * nums[i - 1];
}
int right = 1;
for (int i = n - 1; i >= 0; i--) {
answer[i] *= right;
right *= nums[i];
}
return answer;
}
}
[์๋ ํ์ด ยท gpt-4.1-mini] ๊ฐ ์ธ๋ฑ์ค์์ ์ผ์ชฝ์ ์๋ ๋ชจ๋ ์์ ๊ณฑ๊ณผ ์ค๋ฅธ์ชฝ์ ์๋ ๋ชจ๋ ์์ ๊ณฑ์ ๊ณฑํ๋ฉด ํด๋น ์ธ๋ฑ์ค๋ฅผ ์ ์ธํ ๋ชจ๋ ์์ ๊ณฑ์ ๊ตฌํ ์ ์๋ค. ์ผ์ชฝ ๊ณฑ ๋ฐฐ์ด๊ณผ ์ค๋ฅธ์ชฝ ๊ณฑ ๋ฐฐ์ด์ ๋ง๋ค์ด ํ ๋ฒ์ ๊ณ์ฐํ๊ฑฐ๋, ๊ฒฐ๊ณผ ๋ฐฐ์ด์ ์ด์ฉํด ๊ณต๊ฐ์ ์ ์ฝํ๋ฉฐ ๋ ๋ฒ ์ํํ๋ค. ์๊ฐ O(n) ยท ๊ณต๊ฐ O(1) (์ถ๋ ฅ ๋ฐฐ์ด ์ ์ธ) ์ฃผ์: 0์ด ์ฌ๋ฌ ๊ฐ์ผ ๋ ๊ฒฐ๊ณผ๊ฐ ๋ชจ๋ 0์ด ๋๋ ์ ๊ณผ, ๋๋๊ธฐ ์ฐ์ฐ์ ์ฌ์ฉํ์ง ์์์ผ ํ๋ค๋ ์ ์ ์ฃผ์ํด์ผ ํ๋ค.