Skip to content

Commit 3718532

Browse files
add a solution for 128
1 parent e338d1d commit 3718532

File tree

2 files changed

+44
-5
lines changed

2 files changed

+44
-5
lines changed

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

+41-5
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22

33
import java.util.HashMap;
44
import java.util.HashSet;
5+
import java.util.Iterator;
56
import java.util.Map;
67
import java.util.Set;
8+
import java.util.TreeSet;
79

810
public class _128 {
911
public static class Solution1 {
@@ -104,19 +106,22 @@ public int longestConsecutive(int[] nums) {
104106
}
105107

106108
public static class Solution3 {
109+
/**
110+
* O(n) time complexity.
111+
*/
107112
public int longestConsecutive(int[] nums) {
108-
HashSet<Integer> numSet = new HashSet<>();
113+
Set<Integer> set = new HashSet<>();
109114
for (int num : nums) {
110-
numSet.add(num);
115+
set.add(num);
111116
}
112117

113118
int longestStreak = 0;
114-
for (int num : nums) {
115-
if (!numSet.contains(num - 1)) {
119+
for (int num : set) {//we'll go through this set instead of nums, this makes a big difference in time complexity, esp. based on LeetCode test cases
120+
if (!set.contains(num - 1)) {
116121
int currentNum = num;
117122
int currentStreak = 1;
118123

119-
while (numSet.contains(currentNum + 1)) {
124+
while (set.contains(currentNum + 1)) {
120125
currentNum += 1;
121126
currentStreak += 1;
122127
}
@@ -126,4 +131,35 @@ public int longestConsecutive(int[] nums) {
126131
return longestStreak;
127132
}
128133
}
134+
135+
public static class Solution4 {
136+
/**
137+
* O(nlogn) time complexity
138+
*/
139+
public int longestConsecutive(int[] nums) {
140+
if (nums.length == 0) {
141+
return 0;
142+
}
143+
TreeSet<Integer> treeSet = new TreeSet<>();
144+
for (int i : nums) {
145+
treeSet.add(i);//O(logn) time complexity for each add() call
146+
}
147+
int ans = 1;
148+
Iterator<Integer> it = treeSet.iterator();
149+
Integer curr = it.next();
150+
int len = 1;
151+
while (it.hasNext()) {
152+
Integer next = it.next();
153+
if (curr + 1 == next) {
154+
len++;
155+
} else {
156+
len = 1;
157+
}
158+
curr = next;
159+
ans = Math.max(ans, len);
160+
}
161+
ans = Math.max(ans, len);
162+
return ans;
163+
}
164+
}
129165
}

src/test/java/com/fishercoder/_128Test.java

+3
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,19 @@
88

99
public class _128Test {
1010
private static _128.Solution3 solution3;
11+
private static _128.Solution4 solution4;
1112
private static int[] nums;
1213

1314
@BeforeClass
1415
public static void setup() {
1516
solution3 = new _128.Solution3();
17+
solution4 = new _128.Solution4();
1618
}
1719

1820
@Test
1921
public void test1() {
2022
nums = new int[]{100, 4, 200, 1, 3, 2};
2123
assertEquals(4, solution3.longestConsecutive(nums));
24+
assertEquals(4, solution4.longestConsecutive(nums));
2225
}
2326
}

0 commit comments

Comments
 (0)