💻알고리즘

[LeetCode] 238. Product of Array Except Self

김 진 하 2025. 8. 25. 21:05

문제

정수 배열 nums가 주어졌을 때, answer[i]가 nums[i]를 제외한 nums의 모든 요소의 곱과 같도록 배열 answer를 반환합니다.

nums의 모든 접두사 또는 접미사의 곱은 32비트 정수에 맞게 보장됩니다.

나눗셈 연산을 사용하지 않고 O(n) 시간에 실행되는 알고리즘을 작성해야 합니다.

 

예시

Example 1:
Input: nums = [1,2,3,4]
Output: [24,12,8,6]


Example 2:
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]

 

추가 케이스들이 자꾸 실패해서 헤맸음

 

아이디어

public int[] productExceptSelf(int[] nums) {
    int len = nums.length;
    int[] result = new int[len];

    int prefix = 1;
    for (int i = 0; i < len; i++) {
        result[i] = prefix;
        prefix *= nums[i];
    }

    int suffix = 1;
    for (int i = len - 1; i >= 0; i--) {
        result[i] *= suffix;
        suffix *= nums[i];
    }

    return result;
}

1차 결과