Skip to content

Commit 12738d3

Browse files
committed
update problem
1 parent b9376cd commit 12738d3

File tree

1 file changed

+32
-39
lines changed

1 file changed

+32
-39
lines changed

zh-hans/problem_misc/longest_consecutive_sequence.md

Lines changed: 32 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
11
# Longest Consecutive Sequence
22

3-
## Question
3+
Tags: Array, Union Find, Hard
44

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
76

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/)
89

910
### Problem Statement
1011

1112
Given an unsorted array of integers, find the length of the longest
1213
consecutive elements sequence.
1314

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-
2215
Your algorithm should run in O(_n_) complexity.
2316

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.
2424

2525
## 题解
2626

@@ -29,40 +29,33 @@ Your algorithm should run in O(_n_) complexity.
2929
### Java
3030

3131
```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);
4438
}
4539

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);
5448
}
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);
6053
}
61-
// update lcs
62-
lcs = Math.max(lcs, count);
54+
sets.remove(num);
55+
if (seq > result) result = seq;
6356
}
6457

65-
return lcs;
58+
return result;
6659
}
6760
}
6861
```

0 commit comments

Comments
 (0)