지구정복

[Array] Leetcode - Product of Array Except Self (238) 본문

데이터 엔지니어링 정복/Algorithm

[Array] Leetcode - Product of Array Except Self (238)

eeaarrtthh 2022. 7. 19. 23:59
728x90
반응형

-문제

https://leetcode.com/problems/product-of-array-except-self/

 

Product of Array Except Self - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

-풀이(개인 IDE에서 푼 코드여서 릿코드에서는 변경 필요)

왼쪽 배열과 오른쪽 배열로 푼다.

 

왼쪽 배열

left[0] = nums[0] = 1

left[1] = left[0] * nums[1] = 1 * 1 = 1

left[2] = left[1] * nums[2] = 1 * 2 = 2

left[3] = left[2] * nums[3] = 2 * 3 = 6

 

오른쪽 배열

right[3] = 1

right[2] = right[3] * nums[3] = 4

right[1] = right[2] * nums[2] = 12

right[0] = right[1] * nums[1] = 24

 

정답배열

answer[0] = right[0] * left[0] = 24 * 1 = 24

answer[1] = right[1] * left[1] = 12 * 1 = 12

answer[2] = right[2] * left[2] = 4 * 2 = 8

answer[3] = right[3] * left[3] = 1 * 6

 

 

public class leet238 {
    public static void main(String[] args) {
        //int nums[] = {1, 2, 3, 4};
        int nums[] = {-1, 1, 0, -3, 3};
        
        int n = nums.length;

        int answer[] = new int[n];

        int p = 1;
        //왼쪽 곱셈
        for( int i=0; i<n; i++ ) {
            answer[i] = p;
            p = p * nums[i];
        }

        p = 1;
        //오른쪽 곱셈
        for( int i=n-1; i>=0; i-- ) {
            answer[i] = answer[i] * p;
            p = p * nums[i];
        }

        for( int i=0; i<n; i++ ) {
            System.out.print( answer[i] + " " );
        }
    }
}
728x90
반응형
Comments