首页 > 试题广场 >

最长的可整合子数组的长度

[编程题]最长的可整合子数组的长度
  • 热度指数:16978 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
先给出可整合数组的定义:如果一个数组在排序之后,每相邻两个数的差的绝对值都为1,或者该数组长度为1,则该数组为可整合数组。例如,[5, 3, 4, 6, 2]排序后为[2, 3, 4, 5, 6],符合每相邻两个数差的绝对值都为1,所以这个数组为可整合数组
给定一个数组arr, 请返回其中最大可整合子数组的长度。例如,[5, 5, 3, 2, 6, 4, 3]的最大可整合子数组为[5, 3, 2, 6, 4],所以请返回5

数据范围:,数组中每个数都满足 

要求:时间复杂度为,空间复杂度为
进阶:时间复杂度 ,空间复杂度

注意:本题中子数组的定义是数组中连续的一段区间,例如 [1,2,3,4,5] 中 [2,3,4] 是子数组,[2,4,5] 和 [1,3] 不是子数组

输入描述:
第一行一个整数N,表示数组长度
第二行N个整数,分别表示数组内的元素


输出描述:
输出一个整数,表示最大可整合子数组的长度
示例1

输入

7
5 5 3 2 6 4 3

输出

5
示例2

输入

3
1 4 2

输出

1
作者:B_Hanan
链接:https://www.nowcoder.com/questionTerminal/677a21987e5d46f1a62cded9509a94f2
来源:牛客网
代码如下:
import sys
List=sys.stdin.readlines()
Array=list(map(int,List[1].strip("\n").split(" ")))
sorted_L=sorted(set(Array))
Len=1
Temp=[]
for i in range(len(sorted_L)-1):
    if sorted_L[i+1]-sorted_L[i]==1:
        Len+=1
    else:
        Len=1#子数组计数中断,重新计数     Temp.append(Len)
if Len==len(sorted_L):
    print(Len)
else:
    print(max(Temp))


发表于 2019-09-24 20:10:33 回复(0)
感觉子数组的问题还没有考虑完全
n = eval(input())
ls = list(map(int, input().split()))
ls.sort()
i = 1
count = 1
if len(ls) == 1 or len(ls) == 0:
    print(len(ls))
while i < len(ls):
    if ls[i]-ls[i-1] == 1:
        count += 1
        i += 1
    else:
        i += 1
print(count)
遍历子数组,却超时!
#接收用户输入
N = eval(input())
#接收空格输入整型数组
ls = list(map(int, input().split()))
#最大可整合子数组的长度初始化为0
res_length = 0
while len(ls) > res_length: # 循环遍历子数组
    for i in range(len(ls)):
        tmp = ls[:i+1]
        tmp.sort()
        # 排序后首尾相减加一若等于长度,则可整合
        if tmp[-1]-tmp[0]+1 == len(tmp) and len(tmp)>res_length:
            res_length = len(tmp)
    ls = ls[1:] #每次数组调整为去除第一位元素的新数组
print(res_length)



编辑于 2019-08-12 11:13:48 回复(0)
import sys
n = int(sys.stdin.readline())
ls = list(set(sys.stdin.readline().strip('\n').split(' ')))
ls2 = sorted([i for i in map(int, [i for i in ls])])
#print(n, ls, ls2)
i, count = 1, 1
tmp = count
if len(ls2) == 0:
    print(0)
if len(ls2) == 1:
    print(count)
while i < len(ls2):
    if int(ls2[i]) - int(ls2[i - 1]) == 1:
        count += 1
        tmp = max(tmp, count)
        i += 1
        #print(i, n, count, tmp)
    else:
        count = 1
        i += 1
print(tmp)
#print(n, ls)


发表于 2019-08-02 17:29:51 回复(0)