算法训练 区间k大数查询
时间限制:1.0s 内存限制:256.0MB
问题描述
给定一个序列,每次询问序列中第l个数到第r个数中第K大的数是哪个。
输入格式
第一行包含一个数n,表示序列长度。
第二行包含n个正整数,表示给定的序列。
第三个包含一个正整数m,表示询问个数。
接下来m行,每行三个数l,r,K,表示询问序列从左往右第l个数到第r个数中,从大往小第K大的数是哪个。序列元素从1开始标号。
输出格式
总共输出m行,每行一个数,表示询问的答案。
样例输入
5
1 2 3 4 5
2
1 5 2
2 3 2
1 2 3 4 5
2
1 5 2
2 3 2
样例输出
4
2
2
数据规模与约定
对于30%的数据,n,m<=100;
对于100%的数据,n,m<=1000;
保证k<=(r-l+1),序列中的数<=106。
扫描二维码关注公众号,回复:
2862649 查看本文章
import java.util.Arrays;
import java.util.Scanner;
/**
*
* @author hhit.soft141.xxf
* @date 2017-3-9
*
*/
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] origin = new int[n];
for (int i = 0; i < origin.length; i++) {
origin[i] = scanner.nextInt();
}
int m = scanner.nextInt();
int[] x = new int[3 * m];
for (int i = 0; i < x.length; i++) {
x[i] = scanner.nextInt();
}
for (int i = 0; i < x.length; i++) {
if (i == 0 || i % 3 == 0) {
int k = 0;
int temp = x[i + 1] - x[i] + 1;
int[] result = new int[temp];
for (int j = x[i] - 1; j <= x[i + 1] - 1; j++) {
result[k] = origin[j];
k++;
}
Arrays.sort(result);
System.out.println(result[result.length - x[i + 2]]);
k = 0;
}
}
}
}