Created
June 29, 2017 22:52
-
-
Save jianminchen/1f443cdfdc9ed407258d7f55c940c8bf to your computer and use it in GitHub Desktop.
Leetcode 128 - longest consecutive sequence - using SortedSet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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