Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/1f443cdfdc9ed407258d7f55c940c8bf to your computer and use it in GitHub Desktop.
Save jianminchen/1f443cdfdc9ed407258d7f55c940c8bf to your computer and use it in GitHub Desktop.
Leetcode 128 - longest consecutive sequence - using SortedSet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Leetcode128_LongestConsecutiveSequence_FirstTime
{
/// <summary>
/// code review on June 29, 2017
/// https://leetcode.com/problems/longest-consecutive-sequence/#/description
/// </summary>
class Leetcode128_LongestConsecutiveSequence_FirstTime
{
static void Main(string[] args)
{
}
/// <summary>
/// code review on June 29, 2017
/// Sort those numbers using binary search tree
/// </summary>
/// <param name="nums"></param>
/// <returns></returns>
public int LongestConsecutive(int[] nums)
{
if (nums == null || nums.Length == 0)
{
return 0;
}
var binarySearchTree = new SortedSet<int>(nums);
int maxSequence = 1;
int currentSequence = 1;
int lastNumber = int.MaxValue;
foreach (var number in binarySearchTree)
{
if (lastNumber != int.MaxValue && number == lastNumber + 1)
{
currentSequence++;
}
else
{
currentSequence = 1;
}
maxSequence = Math.Max(maxSequence, currentSequence);
lastNumber = number;
}
return maxSequence;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment