Skip to content

Commit 5ab7cd5

Browse files
authored
added solution and test case for 128 (fishercoder1534#151)
1 parent a07318b commit 5ab7cd5

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,4 +113,28 @@ public int longestConsecutive(int[] nums) {
113113
return max;
114114
}
115115
}
116+
117+
public static class Solution3 {
118+
public int longestConsecutive(int[] nums) {
119+
HashSet<Integer> numSet = new HashSet<>();
120+
for (int num : nums) {
121+
numSet.add(num);
122+
}
123+
124+
int longestStreak = 0;
125+
for (int num : nums) {
126+
if (!numSet.contains(num - 1)) {
127+
int currentNum = num;
128+
int currentStreak = 1;
129+
130+
while (numSet.contains(currentNum + 1)) {
131+
currentNum += 1;
132+
currentStreak += 1;
133+
}
134+
longestStreak = Math.max(longestStreak, currentStreak);
135+
}
136+
}
137+
return longestStreak;
138+
}
139+
}
116140
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._128;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import static org.junit.Assert.assertEquals;
8+
9+
public class _128Test {
10+
private static _128.Solution3 solution3;
11+
private static int[] nums;
12+
13+
@BeforeClass
14+
public static void setup() {
15+
solution3 = new _128.Solution3();
16+
}
17+
18+
@Test
19+
public void test1() {
20+
nums = new int[]{100,4,200,1,3,2};
21+
int result = 4;
22+
assertEquals(4, solution3.longestConsecutive(nums));
23+
}
24+
}

0 commit comments

Comments
 (0)