牛牛的老师给出了一个区间的定义:对于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),表示牛牛的序列,保证序列是递增的。
输出一个整数,表示最少区间个数。
5 1 3 5 6 7
3
import java.util.Scanner;
/**
* 区间表达
* 牛牛的老师给出了一个区间的定义:对于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
* 输出例子1:
* 3
*
* @author shijiacheng
* @date 2018/1/24
*/
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = sc.nextInt();
}
int count = 1;
for (int i = 0; i < n; i++) {
if (i<n-1){
if (array[i]+1!=array[i+1]){
count++;
}
}
}
System.out.println(count);
}
}
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int pre = in.nextInt(); // 记录第一个数 int count = 1; for (int i=1; i<n; i++) { int num = in.nextInt(); if (num - pre != 1) { // 不连续 count++; } pre = num; } System.out.println(count); } }
#include <stdio.h> #include <stdlib.h> int main() { int N; int i,count,j; count=1; while (scanf("%d",&N)!=EOF) { int A[N]; for (i=0; i<N; i++) { scanf("%d",&A[i]); } j=A[0]; i=0; while(i<N){ if (j==A[i]) { j++; i++; } else { count++; j=A[i]; } } } printf("%d\n",count); return 0; }
n = int(input()) arr = list(map(int,input().split())) sum = 0 for i in range(len(arr)-1): if arr[i]+1 != arr[i+1]: sum += 1 print(sum+1)
import java.util.Scanner; public class Main{ public static void main(String args[]){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int [] arr = new int[n]; for(int i = 0; i < n; i++){ arr[i] = in.nextInt(); } if(n <= 1) System.out.print(n); int count = 1; for(int i = 1; i < n; i++){ if(arr[i] > arr[i - 1] + 1) count++; } System.out.println(count); } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int num[] = new int[n]; for(int i=0;i<n;i++) num[i] = scanner.nextInt(); int splitNum=0; boolean end =false; for(int i=0;i<n-1;i++) { if((num[i]+1)!=num[i+1]) { splitNum++; if(i==n-2) splitNum++; } else if(i==n-2) splitNum++; } System.out.println(splitNum); } }