问题描述
给定一个序列,每次询问序列中第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
package ALGO;
import java.util.Arrays;
import java.util.Scanner;
public class ALGO_1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();//序列长度
int[] a = new int[num];
for(int i=0;i<num;i++)
{
a[i] = sc.nextInt();//序列内容
}
int twice = sc.nextInt();
int[][] b = new int[twice][3];//查询次数
for(int i=0;i<twice;i++)//从a到b区间被第k大的数
{
for(int j=0;j<3;j++)
{
b[i][j] = sc.nextInt();
}
}
sc.close();
for(int i=0;i<twice;i++)
{
int[] c = new int[num];
int count = 0;
for(int j=b[i][0]-1;j<b[i][1];j++)
{
c[count] = a[j];
count++;
}
Arrays.sort(c);
System.out.println(c[c.length-b[i][2]]);
}
}
}
import java.util.Arrays;
import java.util.Scanner;
public class ALGO_1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();//序列长度
int[] a = new int[num];
for(int i=0;i<num;i++)
{
a[i] = sc.nextInt();//序列内容
}
int twice = sc.nextInt();
int[][] b = new int[twice][3];//查询次数
for(int i=0;i<twice;i++)//从a到b区间被第k大的数
{
for(int j=0;j<3;j++)
{
b[i][j] = sc.nextInt();
}
}
sc.close();
for(int i=0;i<twice;i++)
{
int[] c = new int[num];
int count = 0;
for(int j=b[i][0]-1;j<b[i][1];j++)
{
c[count] = a[j];
count++;
}
Arrays.sort(c);
System.out.println(c[c.length-b[i][2]]);
}
}
}
一开始我使用的是选择排序,但是运行超时了,后来我改用系统自带的sort,可以运行