42. Trapping Rain Water / Hard / JavaScript #54
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
설명
left와right로 포인터 생성해서 시작height[left]와height[right]중에 작은 쪽의 포인터를 좁혀옮 (left++,right--)maxLeftHeight,maxRightHeight로 기억해두고포인터를 좁혀오면서, trap이 생긴다(=
max___Height보다 낮은 기둥이 나온다)면max___Height에서 수직선을 그었을 때, 그 수직선으로부터 현 기둥까지의 높이차가 trap의 높이가 되므로그만큼을
totalWater에 더한다.left가right보다 커지면 배열 전체를 확인한 것이므로 탐색을 중단하고,totalWater를 반환한다.Time Complexity: O(n)
Space Complexity: O(1)