1
1
# Longest Consecutive Sequence
2
2
3
- ## Question
3
+ Tags: Array, Union Find, Hard
4
4
5
- - leetcode: [ Longest Consecutive Sequence | LeetCode OJ] ( https://leetcode.com/problems/longest-consecutive-sequence/ )
6
- - lintcode: [ (124) Longest Consecutive Sequence] ( http://www.lintcode.com/en/problem/longest-consecutive-sequence/ )
5
+ ## Question
7
6
7
+ - leetcode: [ Longest Consecutive Sequence] ( https://leetcode.com/problems/longest-consecutive-sequence/ )
8
+ - lintcode: [ Longest Consecutive Sequence] ( https://www.lintcode.com/problem/longest-consecutive-sequence/ )
8
9
9
10
### Problem Statement
10
11
11
12
Given an unsorted array of integers, find the length of the longest
12
13
consecutive elements sequence.
13
14
14
- #### Example
15
-
16
- Given ` [100, 4, 200, 1, 3, 2] ` ,
17
- The longest consecutive elements sequence is ` [1, 2, 3, 4] ` . Return its
18
- length: ` 4 ` .
19
-
20
- #### Clarification
21
-
22
15
Your algorithm should run in O(_ n_ ) complexity.
23
16
17
+ ** Example:**
18
+
19
+
20
+
21
+ ** Input:** [ 100, 4, 200, 1, 3, 2]
22
+ ** Output:** 4
23
+ ** Explanation:** The longest consecutive elements sequence is [ 1, 2, 3, 4] . Therefore its length is 4.
24
24
25
25
## 题解
26
26
@@ -29,40 +29,33 @@ Your algorithm should run in O(_n_) complexity.
29
29
### Java
30
30
31
31
``` java
32
- public class Solution {
33
- /**
34
- * @param nums: A list of integers
35
- * @return an integer
36
- */
37
- public int longestConsecutive (int [] num ) {
38
- if (num == null || num. length == 0 ) return 0 ;
39
-
40
- // add number to hashset
41
- Set<Integer > hashset = new HashSet<Integer > ();
42
- for (int n : num) {
43
- hashset. add(n);
32
+ class Solution {
33
+ public int longestConsecutive (int [] nums ) {
34
+ if (nums == null || nums. length <= 0 ) return 0 ;
35
+ Set<Integer > sets = new HashSet<> (nums. length);
36
+ for (int num : nums) {
37
+ sets. add(num);
44
38
}
45
39
46
- int lcs = 0 ;
47
- for (int n : num ) {
48
- int i = n, count = 1 ;
49
- hashset . remove(n) ;
50
- // i--
51
- while (hashset . contains(-- i )) {
52
- count ++ ;
53
- hashset . remove(i );
40
+ int result = 1 ;
41
+ for (int num : nums ) {
42
+ int seq = 1 ;
43
+ int right = num, left = num ;
44
+ // right
45
+ while (sets . contains(++ right )) {
46
+ seq ++ ;
47
+ sets . remove(right );
54
48
}
55
- // i++
56
- i = n;
57
- while (hashset. contains(++ i)) {
58
- count++ ;
59
- hashset. remove(i);
49
+ // left
50
+ while (sets. contains(-- left)) {
51
+ seq++ ;
52
+ sets. remove(left);
60
53
}
61
- // update lcs
62
- lcs = Math . max(lcs, count) ;
54
+ sets . remove(num);
55
+ if (seq > result) result = seq ;
63
56
}
64
57
65
- return lcs ;
58
+ return result ;
66
59
}
67
60
}
68
61
```
0 commit comments