문제
Given n non negative integers representing an elevation map
where the width of each bar is 1, compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by
array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Example 2:
Input: height = [4,2,0,3,2,5]
Output: 9
Constraints:
n == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105
풀이
뭔가 감은 잡히는데 시간 없어서 답을 봤다.
양 끝의 기둥을 기준으로 내부에 채울 수 있는 면적을 구할려 했는데,
투 포인터로 그냥 한칸 한칸 구하면 시간복잡도도 줄이고 코드를 간단하게 짤 수 있다.
답안
/**
* @param {number[]} height
* @return {number}
*/
var trap = function (height) {
const n = height.length;
if (n === 0) return 0;
let left = 0, right = n - 1;
let leftMax = 0, rightMax = 0;
let totalWater = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) {
leftMax = height[left];
}
else {
totalWater += leftMax - height[left];
}
left++;
}
else {
if (height[right] >= rightMax) {
rightMax = height[right];
}
else {
totalWater += rightMax - height[right];
}
right--;
}
}
return totalWater;
};
'JavaScript > Leetcode' 카테고리의 다른 글
Generate Parentheses (Medium) (0) | 2024.10.23 |
---|---|
132 Pattern (Medium) (0) | 2024.10.23 |
Group Anagrams (Medium) (1) | 2024.09.28 |
Container With Most Water (Medium) (0) | 2024.09.27 |
Longest Palindromic Substring (Medium) (1) | 2024.09.26 |