PS/LeetCode

Product of Array Except Self

Hamp 2025. 1. 5. 14:40
반응형

문제

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

입력

2 <= nums.length <= 10^5
-30 <= nums[i] <= 30

결과

ans: [Int] = 자신을 제외한 곱 배열

해석

첫 반복문에서 모든 값을 순회하며 0 개수를 count와 동시에 0을 제외환 모든 곱의 결과를 계산

 

실질적인 계산일 때 2가지 분기로 구분

 

1) 현재 값이 0일 때

- 다른 0이 존재하면 무조건 0, 그렇지 않으면 total

 

2) 현재 값이 0이 아닐 때

- 0이 한번이라도 존재하면 0, 아니면 total / 현재 값  

코드

class Solution {
    func productExceptSelf(_ nums: [Int]) -> [Int] {
        var zeroCount: Int = 0
        let total = nums.reduce(1) { prev, now in
            if now == 0 {
                zeroCount += 1
                return prev 
            } else {
                return prev * now 
            }
        }

        var ans: [Int] = []

        for num in nums {
            var product = 0
            if num == 0 {
                product = zeroCount == 1 ? total : 0
            } else {
                product = zeroCount == 0 ? total/num : 0
            }
            ans.append(product)
        }
        return ans
    }
}

 

반응형