generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem25.cs
More file actions
53 lines (44 loc) · 1.44 KB
/
Problem25.cs
File metadata and controls
53 lines (44 loc) · 1.44 KB
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
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/longest-consecutive-sequence/">Longest Consecutive Sequence</see>.
/// </summary>
public static class Problem25
{
/// <summary>
/// Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
/// You must write an algorithm that runs in O(n) time.
/// Time complexity: O(n).
/// Space complexity: O(n).
/// </summary>
/// <param name="nums">Array to traverse.</param>
/// <returns>Length of the longest consecutive elements sequence.</returns>
public static int LongestConsecutive(int[] nums)
{
var set = new HashSet<int>(nums.Length);
for (var i = 0; i < nums.Length; i++)
{
#pragma warning disable IDE0058
set.Add(nums[i]);
#pragma warning restore IDE0058
}
var maxLength = 0;
for (var i = 0; i < nums.Length; i++)
{
if (set.Remove(nums[i]))
{
var leftCount = 0;
while (set.Remove(nums[i] - leftCount - 1))
{
leftCount++;
}
var rightCount = 0;
while (set.Remove(nums[i] + rightCount + 1))
{
rightCount++;
}
maxLength = Math.Max(maxLength, leftCount + rightCount + 1);
}
}
return maxLength;
}
}