-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path128.longest-consecutive-sequence.java
67 lines (58 loc) · 1.47 KB
/
128.longest-consecutive-sequence.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* @lc app=leetcode id=128 lang=java
*
* [128] Longest Consecutive Sequence
*
* https://leetcode.com/problems/longest-consecutive-sequence/description/
*
* algorithms
* Hard (44.12%)
* Likes: 3158
* Dislikes: 173
* Total Accepted: 294.6K
* Total Submissions: 659.6K
* Testcase Example: '[100,4,200,1,3,2]'
*
* Given an unsorted array of integers, find the length of the longest
* consecutive elements sequence.
*
* Your algorithm should run in O(n) complexity.
*
* Example:
*
*
* Input: [100, 4, 200, 1, 3, 2]
* Output: 4
* Explanation: The longest consecutive elements sequence is [1, 2, 3, 4].
* Therefore its length is 4.
*
*
*/
// @lc code=start
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) set.add(num);
int longest = 0;
for (int num : nums) {
if (!set.contains(num)) continue;
int cnt = 1;
set.remove(num);
int curr = num+1;
while(set.contains(curr)) {
cnt++;
set.remove(curr);
curr++;
}
curr = num-1;
while(set.contains(curr)) {
cnt++;
set.remove(curr);
curr--;
}
longest = Math.max(longest, cnt);
}
return longest;
}
}
// @lc code=end