求最大子序列, 序列未排序
如: {11, 10, 2, 3, 1, 5, 7, 8, 9 } => 5 (7, 8, 9, 10, 11)
除了对数组排序后在进行查找之外,还可以同通过HashMap
Hash
static int GetLongestSequence1(int[] arr)
{
int maxLength = 0;
Hashtable tbl = new Hashtable(); // <number, sequence length>
foreach (var num in arr)
{
if (tbl[num] == null)
{
int currentLength = 1;
if (tbl[num - 1] != null)
{
currentLength = int.Parse(tbl[num - 1].ToString()) + 1;
}
tbl[num] = currentLength;
int currentNum = num;
while (tbl[currentNum + 1] != null)
{
currentLength = int.Parse(tbl[currentNum].ToString()) + 1;
tbl[currentNum + 1] = currentLength;
currentNum++;
}
if (currentLength >maxLength)
{
maxLength = currentLength;
}
}
}
return maxLength;
}