[M] 238. Product of Array Except Self

YJ·2025년 3월 9일

leetcode

목록 보기
15/100

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

문제

배열 주어지면, 자기 빼고 나머지 원소들의 곱을 결과값으로 하는 배열 리턴 (조건: 나누기 금지)

답안

public int[] productExceptSelf(int[] nums) {
	int len = nums.length;
	int[] prefix = new int[len];
	int[] suffix = new int[len];
	int[] ans = new int[len];
	prefix[0] = 1;
	suffix[len - 1] = 1;
	for (int i = 1; i < len; i++) {
		prefix[i] = prefix[i - 1] * nums[i - 1];
	}
	for (int i = len - 2; i >= 0; i--) {
		suffix[i] = suffix[i + 1] * nums[i + 1];
	}
	for (int i = 0; i < len; i++) {
		ans[i] = prefix[i] * suffix[i];
	}
	return ans;
}

prefix array 와 suffix array 만들어서 곱셈

  • prefix array: 해당 원소 왼쪽까지의 값을 모조리 곱한 배열
  • suffix array: 해당 원소 오른쪽까지의 값을 모조리 곱한 배열

메모

profile
Hello

0개의 댓글