2021年7月1日:如何计算数组中连续数字序列的最大长度?

更新于
2026-10-10 03:45:03
0阅读来源:SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计373个文字,预计阅读时间需要2分钟。

2021年7月1日:如何计算数组中连续数字序列的最大长度?

pythondef longest_consecutive(arr): arr.sort() longest=0 current=1 for i in range(1, len(arr)): if arr[i]==arr[i - 1] + 1: current +=1 else: longest=max(longest, current) current=1 longest=max(longest, current) return longest

输入arr=[100, 4, 1, 20, 3, 2, 50]输出print(longest_consecutive(arr))


2021-07-01:最长连续序列。一个未排序的arr,找出数字连续的最长序列的长度。输入:[100,4,1,20,3,2,50],输出:4。解释:最长数字连续序列是[1,2,3,4],所以长度是4。

福大大 答案2021-07-01:

连续区间头表,map1[5]=3,是5,6,7。
连续区间尾表,map2[5]=3,是3,4,5。
求map1中的value最大值,就是需要的返回值。
时间复杂度:O(N)。
空间复杂度:O(N)。

代码用golang编写。

阅读全文

本文共计373个文字,预计阅读时间需要2分钟。

2021年7月1日:如何计算数组中连续数字序列的最大长度?

pythondef longest_consecutive(arr): arr.sort() longest=0 current=1 for i in range(1, len(arr)): if arr[i]==arr[i - 1] + 1: current +=1 else: longest=max(longest, current) current=1 longest=max(longest, current) return longest

输入arr=[100, 4, 1, 20, 3, 2, 50]输出print(longest_consecutive(arr))


2021-07-01:最长连续序列。一个未排序的arr,找出数字连续的最长序列的长度。输入:[100,4,1,20,3,2,50],输出:4。解释:最长数字连续序列是[1,2,3,4],所以长度是4。

福大大 答案2021-07-01:

连续区间头表,map1[5]=3,是5,6,7。
连续区间尾表,map2[5]=3,是3,4,5。
求map1中的value最大值,就是需要的返回值。
时间复杂度:O(N)。
空间复杂度:O(N)。

代码用golang编写。

阅读全文