- ๋ฌธ์ ๋ฅผ ๋ ๋ถ๋ถ์ผ๋ก ๋๋์ด ํ์ด์ผ ํ๋ค๋ ์ ์ ๊นจ๋ซ๋๋ฐ ์ค๋ ๊ฑธ๋ ธ๋ค.
- ์กฐ๊ฑด ๋ฐ ์์๋ฅผ ๊ด์ฐฐํ๋ฉด ์ ์ ์๋ ์ฌํญ์ ์๋์ ๊ฐ๋ค.
- ๋ฌผ์ด ๊ณ ์ฌ์๋ ๋ถ๋ถ์ ์ด์ ์ ์ถ์ฐํ๋ ๋์ด ์ค ๊ฐ์ฅ ํฐ๊ฐ๊ณผ ๊ฐ๊ฑฐ๋ ํด ๊ฒฝ์ฐ ์๊ธด๋ค.
- ๋ฌธ์ ๋ ๊ฐ์ฅ ๋์ด๊ฐ ๋์ ๋ง๋๋ฅผ ๊ธฐ์ค์ผ๋ก ์ค๋ฅธ์ชฝ์์๋ ๋์ด๊ฐ ๋ฎ์ ๊ณณ์์๋ ๋ฌผ์ด ๊ณ ์ด๋ ๋ถ๋ถ์ด ์๊ธด๋ค.
- ๋ฐ๋ผ์ ๋ฌธ์ ๋ ๋์ด๊ฐ ๊ฐ์ฅ ๋์ ๋ง๋๋ฅผ ๊ธฐ์ค์ผ๋ก ์ผ์ชฝ, ์ค๋ฅธ์ชฝ์ผ๋ก ๋๋์ด ์ ๊ทผํ๋ค.
- ๋จผ์ ์ผ์ชฝ์์๋ถํฐ ๋์ด๊ฐ ์ด์ ๊ณผ ๋น๊ตํ์ฌ ๊ฐ๊ฑฐ๋ ๋์ ๋ง๋๊ฐ ๋ฑ์ฅํ ๋ ๋ง๋ค ๊ธฐ๋กํ๋ค.
- ๊ทธ ๋ค์ ๊ฐ์ฅ ๋์ ๋ง๋๋ฅผ ๊ธฐ์ค์ผ๋ก ์ค๋ฅธ์ชฝ ๋ถ๋ถ์ ์ญ๋ฐฉํฅ์ผ๋ก ํ์ํ๋ฉฐ ๋์ด๊ฐ ์ด์ ๊ณผ ๋น๊ตํ์ฌ ๊ฐ๊ฑฐ๋ ๋์ ๋ง๋๊ฐ ๋ฑ์ฅํ ๋ ๋ง๋ค ๊ธฐ๋กํ๋ค.
- ์ด๋ ๊ฒ ๊ธฐ๋ก๋ ๋ง๋์ ๋ง๋ ์ฌ์ด์ ์
๋ฉ์ด์ ๊ณ ์ธ ๋ฌผ์ ์์ ๊ธฐ๋กํ๋ค.
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;
}
};