๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm๐Ÿฐ/๋ฆฌํŠธ์ฝ”๋“œ

[๋ฆฌํŠธ์ฝ”๋“œ] 238. Product of Array Except Self

by Jouureee 2021. 12. 10.

๋ฌธ์ œ :

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

 

Product of Array Except Self - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

๋ถ„์„ :

์ด ๋ฌธ์ œ๋Š” ๊ตฌ๊ฐ„๊ณฑ ๋ฌธ์ œ๋‹ค

์กฐ๊ธˆ ํ‘ธ๋Š” ๋ฐฉ๋ฒ•์ด ์‹ ๊ธฐํ•ด์„œ ๊ธฐ๋กํ•ด๋ณด๋ ค๊ตฌ ํ•œ๋‹ค!! (์ ˆ๋Œ€ ์ƒ๊ฐ๋„ ๋ชปํ•œ ๋ฐฉ๋ฒ• .. ใ… )

 

์ฒ˜์Œ์—” 

์ž๊ธฐ ์ž์‹ ์„ ์ œ์™ธํ•œ ๊ณฒ์ด๋ผ ํ•ด์„œ 

1. nums ๋ฐฐ์—ด์„ ๋ณต์‚ฌํ•œ copyํ•œ ๋ฐฐ์—ด ์ƒ์„ฑ

2. ๋ฐฐ์—ด ๋‚ด ๋ชจ๋“  ๊ณฒ์„ ๊ณฑํ•œ ๋’ค ์ œ์™ธํ•œ index ์œ„์น˜์— ๊ฐ’์„ ์ €์žฅ

์œผ๋กœ ์ƒ๊ฐํ–ˆ๋Š”๋ฐ 1๋ฒˆ๊ณผ 2๋ฒˆ์ด ์ด์ค‘ for๋ฌธ์œผ๋กœ ๋ฌธ์ œ์—์„œ ์ฃผ์–ด์ง„ O(n) ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๋งŒ์กฑ์‹œํ‚ฌ ์ˆ˜ ์—†์—ˆ๋‹ค.

 

์ฝ”๋“œ์— ๋Œ€ํ•œ ์„ค๋ช…์€ 

https://leetcode.com/problems/product-of-array-except-self/discuss/793722/C%2B%2B-Easy-Solution-Meeting-All-Requirements-Explained-~98-Time-95-Space

์ด๋ถ„์˜ ์„ค๋ช…์„ ๋ณด๊ณ  ์ž‘์„ฑํ•˜์˜€๋‹ค.

 

์šฐ์„  ์™ผ์ชฝ์œผ๋กœ ๋Œ๋ฉด์„œ 

res ๋ฐฐ์—ด์˜ ์ด์ „๊ฐ’๊ณผ nums ๋ฐฐ์—ด์˜ ์ด์ „๊ฐ’์„ ๊ณฑํ•œ ๊ฐ’์œผ๋กœ res ๋ฐฐ์—ด์„ ์ดˆ๊ธฐํ™” ํ•ด์ค€๋‹ค.

 

์˜ˆ๋ฅผ ๋“ค์–ด์„œ [1,2,3,4,5,6] ๋ฐฐ์—ด์ด ์žˆ์„๋•Œ

๊ฐ ๋ฐฐ์—ด์˜ ๊ฐ’์€ 

์ด๋ ‡๊ฒŒ ๊ตฌ์„ฑ์ด ๋˜๋Š”๋ฐ ๋ฐ‘์ค„์นœ ๊ฐ’์€ res ๋ฐฐ์—ด์˜ ์ด์ „ ๊ฐ’์ด๋‹ค. ๊ฐ’์€ nums ๋ฐฐ์—ด ์ธ๋ฑ์Šค์— ํ•ด๋‹น๋˜๋Š” ๊ฐ’ ์ „๊นŒ์ง€์˜ ๊ณฒ์œผ๋กœ ๊ณ„์‚ฐ๋˜์—ˆ๊ณ  ๋งˆ์ง€๋ง‰ ์ธ๋ฑ์Šค๋Š” ๊ฒฐ๊ณผ๊ฐ’๊ณผ ๊ฐ™์€ ๊ฒƒ์„ ํ™•์ธ ํ• ์ˆ˜ ์žˆ๋‹ค.

 

๊ทธ๋ฆฌ๊ณ  ์ด์ œ๋Š” res ์˜ 4๋ฒˆ์งธ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ๊ฑฐ๊พธ๋กœ ๊ฐ’์„ ๊ณ„์‚ฐํ•œ๋‹ค. ์–ด๋–ป๊ฒŒ ํ•˜๋‚˜๋ฉด์€ ๋ฏธ๋ฆฌ nums ๋ฐฐ์—ด์˜ ๋งˆ์ง€๋ง‰ ๊ฐ’์ธ prod ๋ฅผ ๊ณฑํ•ด์ฃผ๊ณ  prod ๊ฐ’์„ ํ•ด๋‹น index์˜ nums ๊ฐ’์„ ๊ณฑํ•ด ๋ˆ„์ ์‹œ์ผœ์ค€๋’ค ์ด๋ฅผ res ๋ฐฐ์—ด์— ๊ณฑํ•ด์ค€๋‹ค.

 

๊ทธ๋Ÿฌ๋ฉด ์–ด๋–ค ํšจ๊ณผ๊ฐ€ ์ผ์–ด๋‚˜๋ƒ๋ฉด

๊ฑฐ๊พธ๋กœ ์ž๊ธฐ ์ž์‹ ์˜ nums ๊ฐ’์„ ์ œ์™ธํ•œ ์˜ค๋ฅธ์ชฝ๋ถ€ํ„ฐ์˜ ๊ฐ’์ด ๊ณฑํ•ด์ง€๋Š” ๊ฑธ ํ™•์ธ ํ• ์ˆ˜ ์žˆ๋‹ค.

 

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        
        // setting up the necessary variables
        int len = nums.size(), prod = nums[len - 1];
        vector<int> res(len);
        // ruling out an edge case
        if (!len) return res;
        // initialising res and using it for the first pass
        res[0] = 1;
        // each cell will be the product of the previous and the matching previous value in nums
        for (int i = 1; i < len; i++) res[i] = res[i - 1] * nums[i - 1];
        // second pass, from the right
        for (int i = --len - 1; i >= 0; --i) {
            res[i] *= prod;
            prod *= nums[i];
            // cout << "res " << res[i] << '\n';
            // cout << "prod " << prod << '\n';
        }
        return res;
        }
};

 

 

๊ฐœ๋…์€ ๊ฐ™์ง€๋งŒ ์ด๋ฅผ ํ’€์–ด๋‚ด๋Š” ๋ฐฉ์‹์—์„œ ์ •๋ง ํš๊ธฐ์ ์ธ ๋ฐฉ์‹์ธ๊ฑฐ ๊ฐ™๋‹ค ..!

 

๋Œ“๊ธ€