File tree Expand file tree Collapse file tree
longest-consecutive-sequence Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution {
2+ int [] dp ;
3+ int [] next ;
4+ int n ;
5+ Map <Integer , Integer > location ;
6+
7+ public int longestConsecutive (int [] nums ) {
8+ n = nums .length ;
9+ dp = new int [n ];
10+ next = new int [n ];
11+ location = new HashMap <>();
12+
13+ for (int i = 0 ; i < n ; i ++){
14+ location .put (nums [i ], i );
15+ dp [i ] = -1 ;
16+ }
17+
18+ for (int i = 0 ; i < n ; i ++){
19+ int nextValue = nums [i ] + 1 ;
20+ if (location .containsKey (nextValue )) {
21+ next [i ] = location .get (nextValue );
22+ continue ;
23+ }
24+ next [i ] = -1 ;
25+ }
26+
27+ for (int i = 0 ; i < n ; i ++) {
28+ if (next [i ] == -1 ) {
29+ dp [i ] = 1 ;
30+ continue ;
31+ }
32+ if (dp [next [i ]] == -1 ) {
33+ dp [i ] = 1 + find (next [i ], nums );
34+ continue ;
35+ }
36+ if (dp [next [i ]] != -1 ){
37+ dp [i ] = 1 + dp [next [i ]];
38+ }
39+ }
40+ int answer = 0 ;
41+ for (int i = 0 ; i < n ; i ++){
42+ // System.out.print(dp[i] + " ");
43+ answer = Math .max (answer , dp [i ]);
44+ }
45+ return answer ;
46+ }
47+
48+ public int find (int idx , int [] nums ) {
49+ if (next [idx ] == -1 ) {
50+ dp [idx ] = 1 ;
51+ }
52+ else if (dp [next [idx ]] == -1 ) {
53+ dp [idx ] = 1 + find (next [idx ], nums );
54+ }
55+ else if (dp [next [idx ]] != -1 ) {
56+ dp [idx ] = 1 + dp [next [idx ]];
57+ }
58+ return dp [idx ];
59+ }
60+
61+
62+ }
63+
64+
You can’t perform that action at this time.
0 commit comments