O(n)时间找出无序数组中最长的连续递增序列
来源:互联网 发布:java免费快速开发平台 编辑:程序博客网 时间:2024/05/16 17:38
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); }}
- O(n)时间找出无序数组中最长的连续递增序列
- 无序整形数组,如何找到最长连续序列长度,时间复杂度O(n)
- 设计一个O(n2)时间的算法,找出由n个数组成的序列的最长单调递增子序列。
- 无序数组的最长递增子序列
- 无序数组中最长连续序列
- 在无序序列中找出最长的连续序列 Longest Consecutive Sequence
- 找出无序数组的最长连续子数组
- 找出n个数组成的最长单调递增子序列( 动态规划O(nlogn) )
- 无序数组中找到最长连续子序列
- 数组的最长-不连续-递增子数组-O(nlogn)
- 【难】求数组中最长递增子序列,时间复杂度O(nlogn)
- 求数组中最长连续递增子序列
- 在一个无序的数组中找出最长的等差数列
- 无序序列中O(n)时间复杂度寻找最小(最大)的K个数
- 算法导论 习题15.4-5 15.4-6 找出一个n个数的序列中最长的单调递增子序列
- 1134 最长递增子序列(时间复杂度O(n*log(n))
- 给定无序自然数数组,求最大连续自然数个数,时间复杂度为O(n)
- 给定无序自然数数组,求最大连续自然数个数,时间复杂度为O(n)
- 进程切换(process switch)
- oracle的函数
- oracle的事务处理
- java操作oracle和一些技巧
- 刘伟XML——DTD
- O(n)时间找出无序数组中最长的连续递增序列
- oracle表的管理(数据类型,表创建删除,数据CRUD 操作)
- 头文件 < >与“ ”
- 关于Servlet页面跳转问题
- SQL Server2005重装Performance Monitor Counter Requirement错误解决
- oracle的查询
- jQuery的基本特性和基本概念
- C++ copy constructor 构建
- matlab中变量名与函数名相同时程序有危险