Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.1
2
3
4
5Example:
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.
暴力?排序?哈希?
Approach 1: Brute Force
Time complexity : O(n^3)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15class Solution:
def longestConsecutive(self, nums):
longest_streak = 0
for num in nums:
current_num = num
current_streak = 1
while current_num + 1 in nums:
current_num += 1
current_streak += 1
longest_streak = max(longest_streak, current_streak)
return longest_streak
Approach 2: Sorting
If we can iterate over the numbers in ascending order, then it will be easy to find sequences of consecutive numbers. To do so, we can sort the array.
Time complexity : O(nlgn)
1 | class Solution: |
1 | class Solution { |
Approach 3: HashSet and Intelligent Sequence Building
1 | class Solution: |
1 | class Solution { |