Algorithm
[Algorithm][Array] 문제 풀이 #4 - Product of Array Except Self
Lee David
2022. 7. 17. 22:59
반응형
문제 링크
https://leetcode.com/problems/product-of-array-except-self/
내 풀이
public int[] productExceptSelf(int[] nums) {
if(nums.length == 0) return new int[] {};
int length = nums.length;
int[] result = new int[length];
result[0] = 1;
int fixed = 1;
for (int i = 1; i < length; i++) {
fixed = nums[i - 1] * fixed;
result[i] = fixed;
}
fixed = 1;
for (int j = length - 2; j >= 0; j--) {
fixed = nums[j + 1] * fixed;
result[j] *= fixed;
}
return result;
}
테스트 결과
이 문제는 O(n)의 타임 리미트 + 나누기를 사용하면 안되는 조건이 있어 아무리 생각해도 도저히 모르겠어서 아래 링크를 참조해 문제를 풀었습니다.
해당 내용을 끙끙대며 이해하고 조금 응용하여 위에 코드를 만들었네요.
단순 수학인줄 알았는데 이런 문제가 더 어려운것 같습니다.
반응형