File tree Expand file tree Collapse file tree 1 file changed +14
-12
lines changed Expand file tree Collapse file tree 1 file changed +14
-12
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public int longestConsecutive (int [] nums ) {
3
- Map <Integer , Integer > map = new HashMap <>();
4
- int maxLength = 0 ;
3
+ Set <Integer > set = new HashSet <>();
5
4
for (int num : nums ) {
6
- if (map .containsKey (num )) {
7
- continue ;
5
+ set .add (num );
6
+ }
7
+ int maxLength = 0 ;
8
+ for (int num : set ) {
9
+ if (!set .contains (num - 1 )) {
10
+ int currNum = num ;
11
+ int currentLength = 1 ;
12
+ while (set .contains (currNum + 1 )) {
13
+ currNum ++;
14
+ currentLength ++;
15
+ }
16
+ maxLength = Math .max (currentLength , maxLength );
8
17
}
9
- int left = map .containsKey (num - 1 ) ? map .get (num - 1 ) : 0 ;
10
- int right = map .containsKey (num + 1 ) ? map .get (num + 1 ) : 0 ;
11
- int sum = left + right + 1 ;
12
- maxLength = Math .max (maxLength , sum );
13
- map .put (num , sum );
14
- map .put (num - left , sum );
15
- map .put (num + right , sum );
16
18
}
17
19
return maxLength ;
18
- }
20
+ }
19
21
}
You can’t perform that action at this time.
0 commit comments