1210. 连号区间数 Java题解 (枚举)【第四届蓝桥杯省赛C++B组,JAVA B组】

11 篇文章 0 订阅

输入样例1:

4
3 2 4 1

输出样例1:

7

输入样例2:

5
3 4 2 5 1

输出样例2:

9

样例解释

第一个用例中,有 7 个连号区间分别是:[1,1],[1,2],[1,3],[1,4],[2,2],[3,3],[4,4]
第二个用例中,有 9 个连号区间分别是:[1,1],[1,2],[1,3],[1,4],[1,5],[2,2],[3,3],[4,4],[5,5]


解题思路:

通过控制区间的左右端点,并找出区间中的最大值和最小值,当满足连号区间时,最值差与索引差相等。求区间的最值时可以嵌套在区间中巧妙求出,从而降低复杂度。

Java代码:O(n^3·logn) (超时)

import java.io.*;

public class Main {
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		int []arr = new int[n + 1];
		String[] split = br.readLine().split(" ");
		for(int i = 1; i <= n; i++) {
			arr[i] = Integer.parseInt(split[i - 1]);
		}
		
		int ans = 0;
		for(int i = 1; i <= n; i++) {//枚举左端点
			for(int j = i; j <= n; j++) {//枚举右端点
				
				int []c = new int[n + 1];//拷贝数组
				for(int f = 1; f <= n; f++) {
					c[f] = arr[f];
				}
				
				Arrays.sort(c, i, j + 1);//对数组中的区间排序
				int cnt = j - i + 1;
				if(c[j] - c[i] + 1 == cnt)//最值差等于索引差
					ans++;
			}
		}
		System.out.println(ans);
	}
}

Java代码:O(n^2) (AC)

import java.io.*;

public class Main {
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		int []arr = new int[n + 1];
		String[] split = br.readLine().split(" ");
		for(int i = 1; i <= n; i++) {
			arr[i] = Integer.parseInt(split[i - 1]);
		}
		
		int ans = 0;
		for(int i = 1; i <= n; i++) {//枚举左端点
			int max = arr[i], min = arr[i];//区间中的最值
			for(int j = i; j <= n; j++) {//枚举右端点
				if(arr[j] > max) max = arr[j];
				if(arr[j] < min) min = arr[j];;
				if(max - min == j - i)ans++;//连号时最值差等于索引值差
			}
		}
		System.out.println(ans);
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值