๐Ÿฅž BE
home

42_Trapping Rain Water

๋‹ด๋‹น์ž
์™„๋ฃŒ ์—ฌ๋ถ€
Solved
์š”์•ฝ
๋‚ ์งœ
2024/07/02
ํƒœ๊ทธ
์ž๋ฃŒ๊ตฌ์กฐ
์ด์ง„ํƒ์ƒ‰
๋‚œ์ด๋„
Hard
์ถœ์ฒ˜
LeetCode

์ฝ”๋“œ

class Solution { // ํˆฌํฌ์ธํ„ฐ public int trap(int[] height) { int left = 0, right = height.length -1; int leftMax = 0, rightMax = 0; int water = 0; while (left < right) { if (height[left] < height[right]) { if (height[left] >= leftMax) { // ์™ผ์ชฝ ์ตœ๋Œ€ ๋†’์ด ๊ฐฑ์‹  leftMax = height[left]; } else { // ํ˜„์žฌ ๋†’์ด์™€ ์™ผ์ชฝ ์ตœ๋Œ€ ๋†’์ด์˜ ์ฐจ์ด๋งŒํผ ๋ฌผ์˜ ์–‘ ๋ˆ„์  water += leftMax - height[left]; } left++; } else { if (height[right] >= rightMax) { // ์˜ค๋ฅธ์ชฝ ์ตœ๋Œ€ ๋†’์ด ๊ฐฑ์‹  rightMax = height[right]; } else { // ํ˜„์žฌ ๋†’์ด์™€ ์˜ค๋ฅธ์ชฝ ์ตœ๋Œ€ ๋†’์ด์˜ ์ฐจ์ด๋งŒํผ ๋ฌผ์˜ ์–‘ ๋ˆ„์  water += rightMax - height[right]; } right--; } } return water; } }
Java
๋ณต์‚ฌ

๋ฌธ์ œ ํ•ด๊ฒฐ ์•„์ด๋””์–ด

ํˆฌํฌ์ธํ„ฐ ์ผ๋Š”๋ฐ, ๋ฌธ์ œ ์ดํ•ด๋Š” ๊ธˆ๋ฐฉ ๋ผ๋„ ๊ตฌํ˜„ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ๊นŒ๋‹ค๋กœ์›Œ์„œ ์˜ค๋ž˜ ๊ฑธ๋ ธ๋‹ค.