42. Trapping Rain Water

  • ๋ฌธ์ œ๋ฅผ ๋‘ ๋ถ€๋ถ„์œผ๋กœ ๋‚˜๋ˆ„์–ด ํ’€์–ด์•ผ ํ•œ๋‹ค๋Š” ์ ์„ ๊นจ๋‹ซ๋Š”๋ฐ ์˜ค๋ž˜ ๊ฑธ๋ ธ๋‹ค.
  • ์กฐ๊ฑด ๋ฐ ์˜ˆ์‹œ๋ฅผ ๊ด€์ฐฐํ•˜๋ฉด ์•Œ ์ˆ˜ ์žˆ๋Š” ์‚ฌํ•ญ์€ ์•„๋ž˜์™€ ๊ฐ™๋‹ค.
    • ๋ฌผ์ด ๊ณ ์—ฌ์žˆ๋Š” ๋ถ€๋ถ„์€ ์ด์ „์— ์ถœ์—ฐํ–ˆ๋˜ ๋†’์ด ์ค‘ ๊ฐ€์žฅ ํฐ๊ฐ’๊ณผ ๊ฐ™๊ฑฐ๋‚˜ ํด ๊ฒฝ์šฐ ์ƒ๊ธด๋‹ค.
    • ๋ฌธ์ œ๋Š” ๊ฐ€์žฅ ๋†’์ด๊ฐ€ ๋†’์€ ๋ง‰๋Œ€๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฅธ์ชฝ์—์„œ๋Š” ๋†’์ด๊ฐ€ ๋‚ฎ์€ ๊ณณ์—์„œ๋„ ๋ฌผ์ด ๊ณ ์ด๋Š” ๋ถ€๋ถ„์ด ์ƒ๊ธด๋‹ค.
  • ๋”ฐ๋ผ์„œ ๋ฌธ์ œ๋Š” ๋†’์ด๊ฐ€ ๊ฐ€์žฅ ๋†’์€ ๋ง‰๋Œ€๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์™ผ์ชฝ, ์˜ค๋ฅธ์ชฝ์œผ๋กœ ๋‚˜๋ˆ„์–ด ์ ‘๊ทผํ•œ๋‹ค.
    • ๋จผ์ € ์™ผ์ชฝ์—์„œ๋ถ€ํ„ฐ ๋†’์ด๊ฐ€ ์ด์ „๊ณผ ๋น„๊ตํ•˜์—ฌ ๊ฐ™๊ฑฐ๋‚˜ ๋†’์€ ๋ง‰๋Œ€๊ฐ€ ๋“ฑ์žฅํ•  ๋•Œ ๋งˆ๋‹ค ๊ธฐ๋กํ•œ๋‹ค.
    • ๊ทธ ๋‹ค์Œ ๊ฐ€์žฅ ๋†’์€ ๋ง‰๋Œ€๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฅธ์ชฝ ๋ถ€๋ถ„์€ ์—ญ๋ฐฉํ–ฅ์œผ๋กœ ํƒ์ƒ‰ํ•˜๋ฉฐ ๋†’์ด๊ฐ€ ์ด์ „๊ณผ ๋น„๊ตํ•˜์—ฌ ๊ฐ™๊ฑฐ๋‚˜ ๋†’์€ ๋ง‰๋Œ€๊ฐ€ ๋“ฑ์žฅํ•  ๋•Œ ๋งˆ๋‹ค ๊ธฐ๋กํ•œ๋‹ค.
  • ์ด๋ ‡๊ฒŒ ๊ธฐ๋ก๋œ ๋ง‰๋Œ€์™€ ๋ง‰๋Œ€ ์‚ฌ์ด์˜ ์›…๋ฉ์ด์— ๊ณ ์ธ ๋ฌผ์˜ ์–‘์„ ๊ธฐ๋กํ•œ๋‹ค.
class Solution { public: int trap(vector<int>& height) { vector<pair<int, int>> leftPivots; for (int i = 0; i < height.size(); ++i) { auto h = height[i]; auto topHeight = (!leftPivots.empty()) ? leftPivots.back().first : 0; if (h > 0 && h >= topHeight) leftPivots.emplace_back(h, i); } if (leftPivots.empty()) return 0; auto lastPivot = leftPivots.back(); vector<pair<int, int>> rightPivots; for (int i = height.size() - 1; i > lastPivot.second; --i) { auto h = height[i]; auto topHeight = (!rightPivots.empty()) ? rightPivots.back().first : 0; if (h > 0 && h >= topHeight) rightPivots.emplace_back(h, i); } int result = 0; int prevHeight = 0, currHeight = 0; int start = 0, end = 0; for (int i = 0; i < leftPivots.size(); ++i) { tie(currHeight, end) = leftPivots[i]; for (int j = start + 1; j < end; ++j) { result += prevHeight - height[j]; } start = end; prevHeight = currHeight; } for (int i = rightPivots.size() - 1; i >= 0; --i) { tie(currHeight, end) = rightPivots[i]; for (int j = start + 1; j < end; ++j) { result += currHeight - height[j]; } start = end; } return result; } };
  • ๋‘๋ฒˆ์งธ ํ•ด๋‹ต์€ ๊ธฐ๋กํ•˜์ง€ ์•Š๊ณ  ๋ฐ”๋กœ๋ฐ”๋กœ ๊ณ„์‚ฐํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.
    • ์ด์ „ ๋†’์ด๋ณด๋‹ค ๋†’์€ ๋ง‰๋Œ€๊ฐ€ ๋“ฑ์žฅํ•  ๋•Œ ๋งˆ๋‹ค ๊ณ„์‚ฐ์„ ์ˆ˜ํ–‰ํ•œ๋‹ค.
class Solution { public: int trap(vector<int>& height) { int result = 0; int end = 0, prevHeight = 0, subSum = 0; for (int i = 0; i < height.size(); ++i) { auto h = height[i]; if (h > 0 && h >= prevHeight) { if (prevHeight > 0) result += subSum; subSum = 0; prevHeight = h; end = i; } else { subSum += prevHeight - h; } } if (prevHeight == 0) return 0; prevHeight = 0; for (int i = height.size() - 1; i >= end; --i) { auto h = height[i]; if (h > 0 && h >= prevHeight) { if (prevHeight > 0) result += subSum; subSum = 0; prevHeight = h; } else { subSum += prevHeight - h; } } return result; } };