From d14453fa6c72d103b52a8ad73a36ea6a5d2e87f0 Mon Sep 17 00:00:00 2001 From: Seungjun <60959924+seungjun-green@users.noreply.github.com> Date: Mon, 4 Jul 2022 14:45:17 +0900 Subject: [PATCH] Create 42-Trapping-Rain-Water.swift --- swift/42-Trapping-Rain-Water.swift | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 swift/42-Trapping-Rain-Water.swift diff --git a/swift/42-Trapping-Rain-Water.swift b/swift/42-Trapping-Rain-Water.swift new file mode 100644 index 000000000..8fd569e30 --- /dev/null +++ b/swift/42-Trapping-Rain-Water.swift @@ -0,0 +1,30 @@ +class Solution { + func trap(_ height: [Int]) -> Int { + if height == nil { + return 0 + } + + var res = 0 + var l = 0 + var r = height.count - 1 + + var leftMax = height[l] + var rightMax = height[r] + + while l < r { + if leftMax < rightMax { + l += 1 + leftMax = max(leftMax, height[l]) + res += leftMax - height[l] + } else { + r -= 1 + rightMax = max(rightMax, height[r]) + res += rightMax - height[r] + } + } + + return res + + } + +}
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: