Skip to content

Commit 4fae2c9

Browse files
committed
https://leetcode.com/problems/longest-consecutive-sequence/
1 parent 7a1e96e commit 4fae2c9

File tree

2 files changed

+49
-60
lines changed

2 files changed

+49
-60
lines changed

HardProblems/Longest Consecutive Sequence.cs

Lines changed: 0 additions & 60 deletions
This file was deleted.
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
namespace LeetCode.MediumProblems
2+
{
3+
internal class LongestConsecutiveSequence
4+
{
5+
public int LongestConsecutive(int[] nums)
6+
{
7+
HashSet<int> numSet = new HashSet<int>(nums);
8+
int maxSequenceLength = 0;
9+
10+
foreach (int num in numSet)
11+
{
12+
// Check if current number is the start of a sequence
13+
if (!numSet.Contains(num - 1))
14+
{
15+
int currentLength = 1;
16+
17+
// Extend the sequence forward
18+
while (numSet.Contains(num + currentLength))
19+
{
20+
currentLength++;
21+
}
22+
23+
maxSequenceLength = Math.Max(maxSequenceLength, currentLength);
24+
}
25+
}
26+
27+
return maxSequenceLength;
28+
}
29+
30+
31+
[Test(Description = "https://leetcode.com/problems/longest-consecutive-sequence/")]
32+
[Category("Medium")]
33+
[Category("LeetCode")]
34+
[Category("Longest Consecutive Sequence")]
35+
[TestCaseSource(nameof(Input))]
36+
public void Test1((int Output, int[] Input) item)
37+
{
38+
var response = LongestConsecutive(item.Input);
39+
Assert.That(response, Is.EqualTo(item.Output));
40+
}
41+
42+
public static IEnumerable<(int Output, int[] Input)> Input =>
43+
new List<(int Output, int[] Input)>()
44+
{
45+
(4, [100, 4, 200, 1, 3, 2]),
46+
(2, [0, -1]),
47+
};
48+
}
49+
}

0 commit comments

Comments
 (0)