128. Longest Consecutive Sequence
I solved this problem using C++.
My idea:
use res
to store the result、 count
to store the current sequence length and max
to store the max number of current consecutive.
For loop:
When the sub of two numbers is not greater than 1, we can go to the if statement. If the two numbers are the same, we skip it, or we can add 1 to count
and assign the current number to max
.
When the sub of two numbers is greater than 1, we can compare res
and count
, and assign the larger one to res
. Then we can reset count
to 1 and reset max
to the current number.
Finally, we can return the larger one between res
and count
.
1 |
|
e.g.
input: nums = [9,1,4,7,3,-1,0,5,8,-1,6]
output: 7
explanation:
- sort -> [-1,-1,0,1,3,4,5,6,7,8,9]
- find the longest consecutive sequence:
two sequences:
-1(-1),0,1 -> 3
3,4,5,6,7,8,9 -> 7 - when
max
is -1, andnums[i]
is -1, nowabs
is not greater than 1, so we can go to the if statement. But they are the same, so we skip it.
p.s. if we useif (abs(nums[i] - max) <= 1 && nums[i] != max)
, maybe will go to else statement which is not correct. When they are the same, current consequence is ended and new consequence is started. - when
max
is 1, andnums[i]
is 3, nowabs
is greater than 1, so we can go to the else statement. We can compareres
andcount
, and assign the larger one tores
. Then we can resetcount
to 1 and resetmax
to the current number.
However, this solution is not the best one because it uses O(nlogn) time complexity.
We can use O(n) time complexity to solve this problem.
use unordered_set
use unordered_set
to store the numbers and remove the duplicates.
for the start of the sequence, we can check if num-1
is not in the set. If it is not, we can start counting the length of the sequence from that number.
Then we can check if num+1
is in the set, and if it is, we can increment the current number and the current result. Finally, we can return the max number of current consecutive.
1 |
|
The time complexity is O(n)!
But in fact, when I use this solution, I find the feedback:
However the feedback of the first solution is:
In fact, unordered_set
also takes time…🤣