2
2
3
3
import java .util .HashMap ;
4
4
import java .util .HashSet ;
5
+ import java .util .Iterator ;
5
6
import java .util .Map ;
6
7
import java .util .Set ;
8
+ import java .util .TreeSet ;
7
9
8
10
public class _128 {
9
11
public static class Solution1 {
@@ -104,19 +106,22 @@ public int longestConsecutive(int[] nums) {
104
106
}
105
107
106
108
public static class Solution3 {
109
+ /**
110
+ * O(n) time complexity.
111
+ */
107
112
public int longestConsecutive (int [] nums ) {
108
- HashSet <Integer > numSet = new HashSet <>();
113
+ Set <Integer > set = new HashSet <>();
109
114
for (int num : nums ) {
110
- numSet .add (num );
115
+ set .add (num );
111
116
}
112
117
113
118
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 )) {
116
121
int currentNum = num ;
117
122
int currentStreak = 1 ;
118
123
119
- while (numSet .contains (currentNum + 1 )) {
124
+ while (set .contains (currentNum + 1 )) {
120
125
currentNum += 1 ;
121
126
currentStreak += 1 ;
122
127
}
@@ -126,4 +131,35 @@ public int longestConsecutive(int[] nums) {
126
131
return longestStreak ;
127
132
}
128
133
}
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
+ }
129
165
}
0 commit comments