区间K大数查询

时间:2020-05-06
本文章向大家介绍区间K大数查询,主要包括区间K大数查询使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

蓝桥杯 ALGO-1 区间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
样例输出
4
2
数据规模与约定
对于30%的数据,n,m<=100;

对于100%的数据,n,m<=1000;

保证k<=(r-l+1),序列中的数<=106

import java.util.Scanner;

public class Main{
	static class Node{
		int l;
		int r;
		int k;
	}
	static int n = 0;
	static int m = 0;
	static int[] array = new int[1002];
	public static void main(String args[]){
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		for(int i=1;i<=n;i++){
			array[i] = sc.nextInt();
		}
		m = sc.nextInt();
		Node[] nodes = new Node[m];
		for(int i=0;i<m;i++){
			nodes[i] = new Node();
			nodes[i].l = sc.nextInt();
			nodes[i].r = sc.nextInt();
			nodes[i].k = sc.nextInt();
		}
                sc.close();
		for(int i=0;i<m;i++){
			sort(nodes[i].l, nodes[i].r, nodes[i].k);
		}
	}
	
	private static void sort(int l,int r,int k){
		int[] temp = new int[1002];
		temp = array.clone();
		quickSort(temp, l, r);
		System.out.println(temp[r+1-k]);
	}
	
	private static void quickSort(int[] array,int l,int r){
		if(l>=r){
			return;
		}
		int temp = partition(array,l,r);
		quickSort(array, l, temp-1);
		quickSort(array, temp+1, r);
	}
	
	public static int partition(int[] array,int start,int end){
		int pivot = array[start];
		int left = start;
		int right = end;
		while(left != right){
			while(left < right && array[right] > pivot){
				right--;
			}
			while(left < right && array[left] < pivot){
				left++;
			}
			if(left < right){
				int temp = array[left];
				array[left] = array[right];
				array[right] = temp;
			}
		}
		int temp = array[left];
		array[left] = pivot;
		pivot = temp;
		
		return left;
	}

}

评测结果是运行错误,只能查看第一个输入输出。
输入:

42
18468 6335 26501 19170 15725 11479 29359 26963 24465 5706 28146 23282 16828 9962 492 2996 11943 4828 5437 32392 14605 3903 154 293 12383 17422 18717 19719 19896 5448 21727 14772 11539 1870 19913 25668 26300 17036 9895 28704 23812 31323 
34
3 34 6
26 30 4
9 12 3
4 40 21
30 40 8
11 23 7
15 37 13
11 35 18
11 29 11
15 34 10
11 21 3
22 34 13
16 24 1
5 25 18
11 27 9
17 19 1
15 26 6
33 35 1
36 40 4
20 36 11
19 25 6
6 39 15
18 24 3
5 13 7
24 34 5
5 7 1
6 31 22
10 30 14
41 42 1
16 17 1
23 29 7
32 36 3
2 24 16
10 36 27

输出:

24465
17422
23282
14605
11539
9962
11943
5437
11943
11943
23282
154
32392
2996
11943
11943
5437
19913
17036
12383
293
17036
5437
15725
17422
29359
3903
5448
31323
11943
154
14772
5706
154

运行得到的输出结果与给的output对比是没有问题的,对比截图:

题目上面给的简单样例输入进去也是没有什么问题的。
不知道出了什么问题?求指教。
另外,程序很长的原因是数组排序我使用的是自己写的快速排序,其实这个排序的话可以用Arrays.sort(数组名);实现

原文地址:https://www.cnblogs.com/AIchangetheworld/p/12835710.html