Skip to content

Commit 2d0a81b

Browse files
add a solution for 485
1 parent 263e0d8 commit 2d0a81b

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/main/java/com/fishercoder/solutions/_485.java

+22
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,26 @@ public int findMaxConsecutiveOnes(int[] nums) {
1515
return maxLen;
1616
}
1717
}
18+
19+
public static class Solution2 {
20+
/**
21+
* Apply the sliding window template, i.e. two pointer technique.
22+
*/
23+
public int findMaxConsecutiveOnes(int[] nums) {
24+
int left = 0;
25+
int right = 0;
26+
int ans = 0;
27+
while (right < nums.length) {
28+
while (right < nums.length && nums[right] == 1) {
29+
right++;
30+
}
31+
ans = Math.max(ans, right - left);
32+
while (right < nums.length && nums[right] != 1) {
33+
right++;
34+
}
35+
left = right;
36+
}
37+
return ans;
38+
}
39+
}
1840
}

src/test/java/com/fishercoder/_485Test.java

+3
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,18 @@
88

99
public class _485Test {
1010
private static _485.Solution1 solution1;
11+
private static _485.Solution2 solution2;
1112

1213
@BeforeClass
1314
public static void setup() {
1415
solution1 = new _485.Solution1();
16+
solution2 = new _485.Solution2();
1517
}
1618

1719
@Test
1820
public void test1() {
1921
assertEquals(3, solution1.findMaxConsecutiveOnes(new int[]{1, 1, 0, 1, 1, 1}));
22+
assertEquals(3, solution2.findMaxConsecutiveOnes(new int[]{1, 1, 0, 1, 1, 1}));
2023
}
2124

2225
}

0 commit comments

Comments
 (0)