問題描述
給定一個序列,每次詢問序列中第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
樣例輸出
4
2
數據規模與約定
對於30%的數據,n,m<=100;
對於100%的數據,n,m<=1000;
保證k<=(r-l+1),序列中的數<=106。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int data1 [] = new int[1000];
int data2 [] = new int[1000];
for(int i = 0;i<n;i++) {
data1[i] = scan.nextInt();
}
int m = scan.nextInt();
for(int i = 0;i<m;i++) {
int l = scan.nextInt();
int r = scan.nextInt();
int K = scan.nextInt();
int count = 0;
for(int j = l-1;j<r;j++) {
data2[count ++] =data1[j];
}
Arrays.sort(data2, 0, count);
System.out.println(data2[count - K]);
}
}
}
下面是用容器寫的,但是結果爲超時??不是很明白,數組排序和容器List裏面的排序有何不同??
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
List<Integer> list = new ArrayList<Integer>();
List<Integer> rlist = new ArrayList<Integer>();
for(int i = 0;i<n;i++) {
list.add(i, scan.nextInt());
}
int m = scan.nextInt();
for(int i = 0;i<m;i++) {
int l = scan.nextInt();
int r = scan.nextInt();
int K = scan.nextInt();
for(int j = l - 1; j < r;j++) {
rlist.add(list.get(j));
}
rlist.sort(null);
System.out.println(rlist.get(rlist.size() - K));
rlist.clear();
}
}
}
容器結果:
數組結果: