Algorithm

[leetcode] 238. Product of Array Except Self

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.

 

examples.

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

 

ํ’€์ด ๐Ÿš€

 

์ฒ˜์Œ์—” ์ด์ค‘ ํฌ๋ฌธ์„ ์‚ฌ์šฉํ•ด์„œ i != j์ธ ๊ฒฝ์šฐ์—๋งŒ ๊ณฑํ•ด์„œ ๋ฐฐ์—ด์— ์‚ฝ์ž…ํ•ด์ฃผ์—ˆ๋‹ค.

ํ•˜์ง€๋งŒ ์‹œ๊ฐ„ ์ดˆ๊ณผ ๋ฐœ์ƒ!!

๋”ฐ๋ผ์„œ ๋ชจ๋“  ์ˆ˜๋ฅผ ๋ชจ๋‘ ๊ณฑํ•œ ๋‹ค์Œ, 0์˜ ๊ฐœ์ˆ˜์— ๋”ฐ๋ผ์„œ ๊ตฌ๋ถ„ํ•˜๋Š” ๋ฐฉ์‹์„ ์ทจํ–ˆ๋‹ค.

์ฆ‰, ๋จผ์ € nums๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ๋ชจ๋“  ๊ฐ’์„ ๋‹ค ๊ณฑํ•ด๋‘”๋‹ค. (product)

๋Œ€์‹  0์ธ ๊ฒฝ์šฐ์—๋Š” ๊ณฑํ•˜์ง€ ์•Š๊ณ  zeroCount๋ฅผ ํ•˜๋‚˜ ์˜ฌ๋ ค์ค€๋‹ค.

 

๋งŒ์•ฝ zeroCount > 1์ธ ๊ฒฝ์šฐ์—๋Š” ์ž๊ธฐ ์ž์‹ ์„ ์ œ์™ธํ•˜๋”๋ผ๋„ 0์ด ๋ฌด์กฐ๊ฑด ์กด์žฌํ•œ๋‹ค๋Š” ์˜๋ฏธ์ด๊ธฐ์— ๋ชจ๋‘ 0์ธ ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

๊ทธ๋ ‡์ง€ ์•Š์€ ๊ฒฝ์šฐ์—๋Š” ๋‹ค์‹œ nums๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ, zeroCount == 1์ธ ๊ฒฝ์šฐ์—๋Š” ๋‚ด๊ฐ€ 0์ธ์ง€, ๋‚จ์ด 0์ธ์ง€ ํŒ๋‹จํ•˜์—ฌ ๊ณ„์‚ฐํ•œ๋‹ค.

 

 

์†Œ์Šค์ฝ”๋“œ ๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int zeros = 0;
        int product = 1;
        int[] answer = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                zeros++;
                continue;
            }
            product *= nums[i];
        }
        
        if (zeros > 1) {
            return answer;
        }
        
        for (int i = 0; i < nums.length; i++) {
            if (zeros == 1 && nums[i] == 0) {
                answer[i] = product;
            } else if (zeros == 1 && nums[i] != 0) {
                answer[i] = 0;
            } else {
                answer[i] = product / nums[i];
            }
        }
        return answer;
    }
}