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

Commite3c7c87

Browse files
add a solution for 11
1 parentc850dc9 commite3c7c87

File tree

2 files changed

+35
-10
lines changed

2 files changed

+35
-10
lines changed

‎src/main/java/com/fishercoder/solutions/_11.java

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,38 @@
22

33
publicclass_11 {
44
publicstaticclassSolution1 {
5+
/**
6+
* Time: O(n^2)
7+
* This brute force solution is NOT accepted on LeetCode due to TLE.
8+
*/
9+
publicintmaxArea(int[]height) {
10+
intmaxArea =0;
11+
for (intleft =0;left <height.length -1;left++) {
12+
for (intright =height.length -1;left <right;right--) {
13+
intarea = (right -left) *Math.min(height[left],height[right]);
14+
maxArea =Math.max(maxArea,area);
15+
}
16+
}
17+
returnmaxArea;
18+
}
19+
}
20+
21+
publicstaticclassSolution2 {
22+
/**
23+
* Two pointer technique.
24+
* Well explained here: https://leetcode.com/problems/container-with-most-water/discuss/6100/Simple-and-clear-proofexplanation
25+
*/
526
publicintmaxArea(int[]height) {
627
intmax =0;
7-
inti =0;
8-
intj =height.length -1;
9-
while (i <j) {
10-
max =Math.max(Math.min(height[i],height[j]) * (j -i),max);
11-
if (height[i] <=height[j]) {
12-
// we need to find the shorter one,
13-
// then calculate its area
14-
i++;
28+
intleft =0;
29+
intright =height.length -1;
30+
while (left <right) {
31+
max =Math.max(Math.min(height[left],height[right]) * (right -left),max);
32+
if (height[left] <=height[right]) {
33+
/**if this height is shorter, then we'll need to move it to the right to find a higher one so that it's possible to find a larger area.*/
34+
left++;
1535
}else {
16-
j--;
36+
right--;
1737
}
1838
}
1939
returnmax;

‎src/test/java/com/fishercoder/_11Test.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,22 @@
88

99
publicclass_11Test {
1010
privatestatic_11.Solution1solution1;
11+
privatestatic_11.Solution2solution2;
1112
privatestaticint[]height;
13+
privatestaticintexpected;
1214

1315
@BeforeClass
1416
publicstaticvoidsetup() {
1517
solution1 =new_11.Solution1();
18+
solution2 =new_11.Solution2();
1619
}
1720

1821
@Test
1922
publicvoidtest1() {
2023
height =newint[]{1,1};
21-
assertEquals(1,solution1.maxArea(height));
24+
expected =1;
25+
assertEquals(expected,solution1.maxArea(height));
26+
assertEquals(expected,solution2.maxArea(height));
2227
}
2328

2429
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp