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 :
Output is :
The solution needs to be of O(n) complexity.
我使用python的的实现代码:
方便理解,我附上别人同样的思想c#的代码:
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); } }
相关文章推荐
- 无序整形数组,如何找到最长连续序列长度,时间复杂度O(n)
- 给定一个长度为N的数组,找出一个最长的单调自增子序列(不一定连续,但是顺序不能乱).
- 【难】求数组中最长递增子序列,时间复杂度O(nlogn)
- 数组最长连续递增(+1)子序列
- 找出数组中最长的连续数字序列(JavaScript实现)
- 128. Longest Consecutive Sequence *HARD* -- 寻找无序数组中最长连续序列的长度
- 给定一个长度为N的数组,找出一个最长的单调自增子序列(不一定连续,但是顺序不能乱). 第二解
- JavaScript实现找出数组中最长的连续数字序列
- 在无序序列中找出最长的连续序列 Longest Consecutive Sequence
- 无序数组中最长连续序列
- 一个无序整数数组中找到最长连续序列(Longest Consecutive Sequence)和两个元素使得相差最小
- 设计一个O(n2)时间的算法,找出由n个数组成的序列的最长单调递增子序列。
- 最长公共子序列|最长公共子串|最长重复子串|最长不重复子串|最长回文子串|最长递增子序列|最大子数组和
- 给一个数组,找出数组中最长的连续数列的长度
- 最长公共子序列|最长公共子串|最长重复子串|最长不重复子串|最长回文子串|最长递增子序列|最大子数组和
- 求数组中最长递增子序列的长度
- 动态规划-数组最长递增子序列长度
- 求数组中最长递增子序列的长度
- 任意区间的最长连续递增子序列,最大连续子序列和