您的位置:首页 > 其它

O(n)时间找出无序数组中最长的连续递增序列

2012-12-23 13:48 519 查看
 You
are given an Array of numbers and they are unsorted/random order. You are supposed to find the longest sequence of consecutive numbers
in the array. Note the sequence need not be in sorted order within the array. Here is an example :

Input :
A[] = {10,21,45,22,7,2,67,19,13,45,12,11,18,16,17,100,201,20,101}


Output is :
{16,17,18,19,20,21,22}


The solution needs to be of O(n) complexity.

我使用python的的实现代码:

def findLongSeq(values):
value_set = set(values)
max_len = 0

while len(value_set) > 0:
value = value_set.pop()
end = start = value
end_cnt = start_cnt = 1

try:
while 1:
value_set.remove(start-1)
start_cnt += 1
start -= 1
except:
pass

try:
while 1:
value_set.remove(end+1)
end_cnt += 1
end += 1
except:
pass

len_seq = end_cnt - start_cnt + 1
if len_seq > max_len:
max_len = len_seq
start_value = value

print "max len is", max_len, "start_value is", start_value

findLongSeq([10,21,45,22,7,2,67,19,13,45,12,11,18,16,17,100,201,20,101])


方便理解,我附上别人同样的思想c#的代码:

using System;
using System.Collections.Generic;
using System.Linq;

class Test
{
static void Main(string[] args)
{
int[] input = {10,21,45,22,7,2,67,19,13,45,12,
11,18,16,17,100,201,20,101};

HashSet<int> values = new HashSet<int>(input);

int bestLength = 0;
int bestStart = 0;
// Can't use foreach as we're modifying it in-place
while (values.Count > 0)
{
int value = values.First();
values.Remove(value);
int start = value;
while (values.Remove(start - 1))
{
start--;
}
int end = value;
while (values.Remove(end + 1))
{
end++;
}

int length = end - start + 1;
if (length > bestLength)
{
bestLength = length;
bestStart = start;
}
}
Console.WriteLine("Best sequence starts at {0}; length {1}",
bestStart, bestLength);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐