๋ฌธ์ :
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) ์๊ฐ ๋ณต์ก๋๋ฅผ ๋ง์กฑ์ํฌ ์ ์์๋ค.
์ฝ๋์ ๋ํ ์ค๋ช ์
์ด๋ถ์ ์ค๋ช ์ ๋ณด๊ณ ์์ฑํ์๋ค.
์ฐ์ ์ผ์ชฝ์ผ๋ก ๋๋ฉด์
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;
}
};
๊ฐ๋ ์ ๊ฐ์ง๋ง ์ด๋ฅผ ํ์ด๋ด๋ ๋ฐฉ์์์ ์ ๋ง ํ๊ธฐ์ ์ธ ๋ฐฉ์์ธ๊ฑฐ ๊ฐ๋ค ..!
'Algorithm๐ฐ > ๋ฆฌํธ์ฝ๋' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฆฌํธ์ฝ๋] 98. Validate Binary Search Tree - BT (0) | 2021.08.17 |
---|---|
[๋ฆฌํธ์ฝ๋] 76. Minimum Window Substring (์ฌ๋ผ์ด๋ฉ ์๋์ฐ) (0) | 2021.08.05 |
[๋ฆฌํธ์ฝ๋] 3. Longest Substring Without Repeating Characters (0) | 2021.07.16 |
[๋ฆฌํธ์ฝ๋] 1. Two Sum (๋์์ ํฉ) (0) | 2021.07.12 |
๋๊ธ