首页 > 试题广场 >

区间表达

[编程题]区间表达
  • 热度指数:5890 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
牛牛的老师给出了一个区间的定义:对于x ≤ y,[x, y]表示x到y之间(包括x和y)的所有连续整数集合。例如[3,3] = {3}, [4,7] = {4,5,6,7}.牛牛现在有一个长度为n的递增序列,牛牛想知道需要多少个区间并起来等于这个序列。
例如:
{1,2,3,4,5,6,7,8,9,10}最少只需要[1,10]这一个区间
{1,3,5,6,7}最少只需要[1,1],[3,3],[5,7]这三个区间

输入描述:
输入包括两行,第一行一个整数n(1 ≤ n ≤ 50),
第二行n个整数a[i](1 ≤ a[i] ≤ 50),表示牛牛的序列,保证序列是递增的。


输出描述:
输出一个整数,表示最少区间个数。
示例1

输入

5
1 3 5 6 7

输出

3
while True:
    try:
        n=int(input().strip())
        inp=list(map(int,input().strip().split(' ')))
        #print(inp)
        num=0
        for i in range(n-1):
            if inp[i]+1 not in inp:
                num+=1
        print(num+1)
    except:
        break
编辑于 2019-07-26 14:19:12 回复(0)
n = int(input())
a = list(map(int, input().split()))
num = 1
for i in range(1, n):
    if a[i] - a[i-1] > 1:
        num += 1
print(num)

发表于 2019-04-11 19:12:00 回复(0)
n=int(input())
seq=list(map(int,input().split()))
res=1
i=0
while i<n-1:
    if seq[i]+1!=seq[i+1]:
        i+=1
        res+=1
    else:
        i+=1
print(res)

编辑于 2019-03-29 17:01:18 回复(0)


n = int(input())
a = list(map(int, input().split()))
count = 0 for i in range(n-1):  if a[i+1] - a[i] != 1:
        count += 1 print(count+1)


发表于 2019-03-19 20:33:21 回复(0)

python 解法

n, arr = int(input()), list(map(int, input().split()))
res = 1
for i in range(1, n):
    if arr[i] - arr[i - 1] > 1:
        res += 1
print(res)

遍历数组,如果某一个数和前一个数的差大于1,那么一定要开辟新的区间。等于1不做任何处理。

发表于 2019-02-24 19:06:42 回复(0)
n = int(raw_input())
s = map(int,raw_input().split())
result = 0
i = 0
while i < n:
    while i+1<n and s[i+1]-s[i]==1:
        i += 1
    result += 1
    i += 1
print(result)

发表于 2019-01-31 10:40:13 回复(0)