Algorithm/문제풀이

[LeetCode#238] Product of Array Except Self

gilbert9172 2024. 7. 23. 23:39

 Description


제목 Product of Array Except Self
링크 https://leetcode.com/problems/product-of-array-except-self/description/
자료구조 선형 자료구조
푼 횟수 7/23

 

이번 문제는 나누기를 하지말라는 제한 조건과 시간복작도 O(n)을 넘기지 말라는 요구사항이 있었다.

 

 

 

Solution


public static int[] solve(int[] nums) {
    int[] result = new int[nums.length];
    int p = 1;
    for (int i = 0; i < nums.length; i++) {
        result[i] = p;
        p *= nums[i];
    }

    p = 1;
    for (int i = nums.length - 1; i >= 0; i--) {
        result[i] *= p;
        p *= nums[i];
    }
    return result;
}

자기 자신을 제외한 왼쪽의 곱셈 결과와 오른쪽의 곱셈 결과를 곱해서 해결하는 문제이다.