Skip to content

Commit 0808323

Browse files
committed
[LeetCode][P128]Longest Consecutive Sequence
1 parent 5e23862 commit 0808323

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

leetcode/src/algorithms/Solution.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
3+
public int longestConsecutive(int[] nums) {
4+
5+
Set<Integer> num_set = new HashSet<Integer>();
6+
for (int num : nums) {
7+
num_set.add(num);
8+
}
9+
10+
int longestStreak = 0;
11+
12+
for (int num : num_set) {
13+
if (!num_set.contains(num-1)) {
14+
int currentNum = num;
15+
int currentStreak = 1;
16+
17+
while (num_set.contains(currentNum+1)) {
18+
currentNum += 1;
19+
currentStreak += 1;
20+
}
21+
22+
longestStreak = Math.max(longestStreak, currentStreak);
23+
}
24+
}
25+
26+
return longestStreak;
27+
}
28+
29+
}

leetcode/src/algorithms/readme.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
128. Longest Consecutive Sequence
2+
3+
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
4+
5+
You must write an algorithm that runs in O(n) time.
6+
7+
8+
9+
Example 1:
10+
11+
Input: nums = [100,4,200,1,3,2]
12+
Output: 4
13+
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
14+
Example 2:
15+
16+
Input: nums = [0,3,7,2,5,8,4,6,0,1]
17+
Output: 9
18+
19+
20+
Constraints:
21+
22+
0 <= nums.length <= 105
23+
-109 <= nums[i] <= 109

0 commit comments

Comments
 (0)