Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitaa4ab7a

Browse files
author
applewjg
committed
TrappingRainWater
Change-Id: I401b52fa8129dc2282cb1248e5feb40cfc9c9f49
1 parentfde517c commitaa4ab7a

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

‎TrappingRainWater.java

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
Author: King, higuige@gmail.com
3+
Date: Oct 07, 2014
4+
Problem: Trapping Rain Water
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/trapping-rain-water/
7+
Notes:
8+
Given n non-negative integers representing an elevation map where the width of
9+
each bar is 1, compute how much water it is able to trap after raining.
10+
For example,
11+
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
12+
13+
Solution: 1. Find left bound and right bound for each element. O(n).
14+
2. more space efficiency. Time: O(n), Space: O(1);
15+
*/
16+
publicclassSolution {
17+
publicinttrap_1(int[]A) {
18+
intn =A.length;
19+
if (n ==0)return0;
20+
int[]maxLeft =newint[n];
21+
int[]maxRight =newint[n];
22+
maxLeft[0] =A[0];
23+
maxRight[n -1] =A[n -1];
24+
for (inti =1;i <n; ++i) {
25+
maxLeft[i] =Math.max(maxLeft[i -1],A[i]);
26+
maxRight[n -1 -i] =Math.max(maxRight[n -i],A[n -1 -i]);
27+
}
28+
29+
intres =0;
30+
for (inti =1;i <n; ++i) {
31+
res +=Math.min(maxLeft[i],maxRight[i]) -A[i];
32+
}
33+
returnres;
34+
}
35+
publicinttrap(int[]A) {
36+
intn =A.length,res =0;
37+
if (n <=2)return0;
38+
intmaxLeft =A[0];
39+
intmaxRight =A[n -1];
40+
intleft =0,right =n -1;
41+
while (left <=right) {
42+
if (maxLeft <=maxRight) {
43+
res +=Math.max(0,maxLeft -A[left]);
44+
maxLeft =Math.max(maxLeft,A[left]);
45+
++left;
46+
}else {
47+
res +=Math.max(0,maxRight -A[right]);
48+
maxRight =Math.max(maxRight,A[right]);
49+
--right;
50+
}
51+
}
52+
returnres;
53+
}
54+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp