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

这篇博客介绍了如何在O(n)的时间复杂度内找到一个无序数组中最长的连续递增序列。博主提供了一个Python实现的解决方案,并通过示例解释了算法的工作原理。
摘要由CSDN通过智能技术生成

 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);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值