본문 바로가기
Problem Solving/리트코드

[리트코드 leetcode] 42. Trapping Rain Water

by ggyongi 2021. 4. 12.
반응형


Problem : leetcode.com/problems/trapping-rain-water/

 

Trapping Rain Water - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


Solution:

class Solution:
    def trap(self, height: List[int]) -> int:
        left = right = 0
        
        left_h = []
        right_h = []
        
        for value in height:
            left = max(value,left)
            left_h.append(left)
            
        for value in height[::-1]:
            right = max(value,right)
            right_h.append(right)
        
        right_h = right_h[::-1]
        
        output =0
        
        for i in range(len(height)):
            output += min(left_h[i],right_h[i])-height[i]
            
        return output

 

and this is time out... 

class Solution:
    def trap(self, height: List[int]) -> int:
        
        if len(height) != 0:
             max_height = max(height)
        else:
            max_height=0
        count = 0
        
        for floor in range(1,max_height+1):
            i=0
            while True:
                if floor <= height[i]:
                    left_boundary = i
                    break    
                i+=1
            
            j=-1
            while True:
                if floor <= height[j]:
                    right_boundary = j +len(height)
                    break    
                j-=1
            
            for k in range(left_boundary+1, right_boundary):
                if height[k]<floor:
                    count+=1
                       
        return count    
                    
            
 

비전공자 네카라 신입 취업 노하우

시행착오 끝에 얻어낸 취업 노하우가 모두 담긴 전자책!

kmong.com

댓글