[LeetCode / Medium] 238. Product of Array Except Self (Java)

이하얀·2025년 2월 8일
0

📙 LeetCode

목록 보기
9/13

💬 Info



Problem

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.



Example

예시 1

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

예시 2

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


Constraints

  • 2 <= nums.length <= 10510^5
    -30 <= nums[i] <= 30
  • The input is generated such that answer[i] is guaranteed to fit in a 32-bit integer.


문제 이해

  • 자기 자신을 제외한 요소를 곱해 그 결과를 출력하면 되는 문제
    • 나눗셈을 하지 않은 상태로 O(n) 연산 필요



알고리즘

풀이 시간 : 40분

  • 왼쪽 곱셈 결과 저장: result[i]에 왼쪽 곱셈 결과 저장
  • 오른쪽 곱셈 결과 적용: 오른쪽 곱셈 결과를 result[i]에 곱해 최종값 출력
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] result = new int[n];

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

        int right = 1;
        for (int i = n - 1; i >= 0; i--) {
            result[i] *= right;
            right *= nums[i];
        }
        return result;
    }
}


결과


profile
언젠가 내 코드로 세상에 기여할 수 있도록, Data Science&BE 개발 기록 노트☘️

0개의 댓글