Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- 출처 따배도
- WAS웹서버
- 스프링부트api
- 스프링부트팔로잉
- 스프링부트중복예외처리
- 스프링부트팔로우취소
- 스프링부트구독취소
- 스프링부트
- 우분투도커설치
- 출처 문어박사
- vm도커설치하는법
- dockerinstall
- 스프링익셉션처리
- 도커설치하는법
- ssh도커설치
- centos도커설치
- 서버에도커설치
- 스프링구독
- 스프링사진
- 출처 메타코딩
- 파이썬sort
- 멀티폼
- 스프링이미지업로드
- 인스타클론
- 출처 코딩셰프
- springboot_exception_handler
- 출처 노마드코더
- 스프링부트사진올리기
- 스프링사진업로드
- 스프링부트서버에사진전송
Archives
- Today
- Total
MakerHyeon
[LeetCode] 42. Trapping Rain Water (python) 본문
https://leetcode.com/problems/trapping-rain-water/description/
Trapping Rain Water - LeetCode
Can you solve this real interview question? Trapping Rain Water - 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: [https://assets.leetcode.com/upl
leetcode.com
투포인터를 이용한다는 건 알겠는데, 구현을 생각해내는게 어려운문제...
여기서 헷갈린건 왜 min pointer를 이동하지?라는 의문이었다.
이 문제는 투 포인터를 최대를 향해 이동시킨다.
즉, 더 높은 쪽을 향해 투포인터를 이동시켜야한다.
예를들어 left_max < right_max인 경우 right_max가 최대 높이일 확률이 있으니 left 포인터가 이동해야 한다.
SOLUTION CODE
# PYTHON
class Solution:
def trap(self, height: List[int]) -> int:
# 예외처리
if not height:
return 0
l, r = 0, len(height) - 1
leftMax, rightMax = height[l], height[r]
res = 0
while l < r:
if leftMax < rightMax: # left가 작다면
l += 1 # 최대를 향해 포인터 업데이트
leftMax = max(leftMax,height[l]) # max값 update
res += leftMax - height[l]
else:
r -= 1
rightMax = max(rightMax, height[r])
res += rightMax - height[r]
return res
- 직관적 코드
class Solution:
def trap(self, height: List[int]) -> int:
result = 0
max_left = height[0]
max_right = height[-1]
start = 1
end = len(height) - 2
while start <= end:
max_left = max(max_left, height[start])
max_right = max(max_right, height[end])
if max_left < max_right:
result = result + max_left - height[start]
start = start + 1
else:
result = result + max_right - height[end]
end = end - 1
return result
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode] 3. Longest Substring Without Repeating Characters (0) | 2023.04.25 |
---|---|
[LeetCode] 121. Best Time to Buy and Sell Stock (0) | 2023.04.19 |
[LeetCode] 11. Container With Most Water (python) (0) | 2023.04.06 |
[LeetCode] 15. 3Sum (python,C++) (0) | 2023.03.14 |
[LeetCode] 1472. Design Browser History (python,C++) (0) | 2023.03.13 |
Comments