[Leetcode] 42. Trapping Rain Water
[Leetcode] 42. Trapping Rain Water

[Leetcode] 42. Trapping Rain Water

์–ธ์–ด
Python
C
๋‚œ์ด๋„
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜ ์œ ํ˜•
์ž‘์„ฑ์ž
๋ฐ•์šฉ์„ฑ๋ฐ•์šฉ์„ฑ
์ƒ์„ฑ ์ผ์‹œ
2024๋…„ 06์›” 02์ผ
ย 

๐Ÿ–ฅ๏ธย ์‹œ์ž‘ํ•˜๋ฉฐ

์ฒ˜์Œ ์ ‘๊ทผ์ด ์–ด๋ ค์› ๋˜ ๋ฌธ์ œ์˜€๋‹ค.
ย 
์šฐ์„  height ๋ฐฐ์—ด์— ๊ฒ€์€์ƒ‰ ๋ธ”๋Ÿญ์˜ ๋†’์ด๊ฐ€ ์ฃผ์–ด์ง€๊ณ , ๋น„๊ฐ€ ์™”์„ ์‹œ ์›…๋ฉ์ด๊ฐ€ ์ƒ๊ธฐ๋Š” ์นธ์ด ๋ช‡ ์นธ์ธ์ง€ ๋‹ต์„ ๋„์ถœํ•ด์•ผ ํ•˜๋Š” ๋ฌธ์ œ๋‹ค.
ย 
notion image
์•„๋งˆ ์ง๊ด€์ ์œผ๋กœ๋Š” ์™ผ์ชฝ ๋ฒฝ๊ณผ ์˜ค๋ฅธ์ชฝ ๋ฒฝ ์ค‘ ๋‚ฎ์€ ๋ฒฝ์˜ ๋†’์ด๋กœ ๋ฐ”๋กœ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ์ง€ ์•Š๋‚˜ ์‹ถ๋‹ค.
ย 
๊ทธ๋ž˜์„œ ๋ณธ์ธ์€ ์™ผ์ชฝ ๋ฒฝ์˜ ์ตœ๋Œ€ ๋†’์ด๋ฅผ ์ €์žฅํ•˜๋Š” ๋ฐฐ์—ด, ์˜ค๋ฅธ์ชฝ ๋ฒฝ์˜ ์ตœ๋Œ€ ๋†’์ด๋ฅผ ์ €์žฅํ•˜๋Š” ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•˜๋Š” ์ชฝ์œผ๋กœ ๊ฐ€๋‹ฅ์„ ์žก์•˜๋‹ค.
ย 
์•„๋ž˜ ๊ทธ๋ฆผ์„ ์ค‘์‹ฌ์œผ๋กœ ํŒŒํ—ค์ณ๋ณด์ž.
notion image
๊ฒฐ๊ตญ ์ด๋ฅผ ์‹์œผ๋กœ ํ’€์–ด๋‚ด์ž๋ฉด
์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ๋ฒฝ์˜ ์ตœ์†Ÿ๊ฐ’ - ๊ฒ€์€์ƒ‰ ๋ธ”๋ก ๋†’์ด ๋ผ๊ณ  ํ•  ์ˆ˜ ์žˆ๋‹ค.
ย 

Python

class Solution: def trap(self, height: List[int]) -> int: if not height: return 0 res = 0 H = len(height) leftMax = [0] * H rightMax = [0] * H # ์™ผ์ชฝ ์ตœ๋Œ€ ๋†’์ด ๋ฒฝ ์ €์žฅ leftMax[0] = height[0] for i in range(1, H): leftMax[i] = max(leftMax[i - 1], height[i]) # ์˜ค๋ฅธ์ชฝ ์ตœ๋Œ€ ๋†’์ด ๋ฒฝ ์ €์žฅ rightMax[H - 1] = height[H - 1] for i in range(H - 2, -1, -1): rightMax[i] = max(rightMax[i + 1], height[i]) # ๊ณ„์‚ฐ for i in range(H): res += min(leftMax[i], rightMax[i]) - height[i] return res

C++

class Solution { public: int trap(const std::vector<int>& height) { if (height.empty()) { return 0; } int H = height.size(); int res = 0; std::vector<int> leftMax(H); std::vector<int> rightMax(H); // ์™ผ์ชฝ์—์„œ๋ถ€ํ„ฐ ์ตœ๋Œ€ ๋†’์ด ์ €์žฅ leftMax[0] = height[0]; for (int i = 1; i < H; ++i) { leftMax[i] = std::max(leftMax[i - 1], height[i]); } // ์˜ค๋ฅธ์ชฝ์—์„œ๋ถ€ํ„ฐ ์ตœ๋Œ€ ๋†’์ด ์ €์žฅ rightMax[H - 1] = height[H - 1]; for (int i = H - 2; i >= 0; --i) { rightMax[i] = std::max(rightMax[i + 1], height[i]); } // ๋ฌผ์„ ์žก์„ ์ˆ˜ ์žˆ๋Š” ์–‘ ๊ณ„์‚ฐ for (int i = 0; i < H; ++i) { res += std::min(leftMax[i], rightMax[i]) - height[i]; } return res; } };
ย 
ย 

์†Œ๊ฐ

DP๋‚˜ ๋‹ค๋ฅธ ๋ฐฉ์‹์„ ๋– ์˜ฌ๋ฆฌ๋‹ค๊ฐ€ ์‹œ๊ฐ„์ด ๋งŽ์ด ๊ฑธ๋ ธ๋‹ค. ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋‹ค์‹œ ์ค€๋น„ํ•˜๋Š”๊ฑธ๋กœ..
ย 

๋ถ€๋ก

์ฐธ๊ณ ๋ฌธํ—Œ


ย 

๋Œ“๊ธ€

guest