File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .*;
2+
3+ class Solution {
4+ public int longestConsecutive (int [] nums ) {
5+ Set <Integer > table = new HashSet <>();
6+ int longest = 0 ;
7+
8+ for (int n : nums ) {
9+ table .add (n );
10+ }
11+
12+ // O(N)
13+ for (int num : table ) {
14+ if (!table .contains (num - 1 )) {
15+ int currentNum = num ;
16+ int currentStreak = 1 ;
17+
18+ while (table .contains (currentNum + 1 )) {
19+ currentNum ++;
20+ currentStreak ++;
21+ }
22+ longest = Math .max (longest , currentStreak );
23+ }
24+ }
25+
26+ /** TIME OUT 발생!
27+ *
28+ for (int n : nums) {
29+ if (table.contains(n - 1)) continue;
30+ int len = 1;
31+ while (table.contains(n + len)){
32+ len++;
33+ }
34+ longest = Math.max(len, longest);
35+ }
36+ */
37+
38+ return longest ;
39+ }
40+ }
You can’t perform that action at this time.
0 commit comments