ALGO-1 区间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.Arrays;
import java.util.Scanner;

public class ALGO_1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int arr[] = new int[n];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = sc.nextInt();
        }
        int time = sc.nextInt();//指定询问个数
        for (int i = 0; i < time; i++) {
            int start = sc.nextInt();
            int end = sc.nextInt();
            int k = sc.nextInt();
            //输入起始位置、结束位置、指定索引元素
            int temp[] = new int[end - start + 1];
            int index = 0;
            //将指定范围元素赋给新的数组
            for (int j = start - 1; j <= end - 1; j++) {
                temp[index++] = arr[j];
            }
            Arrays.sort(temp);//对该数组进行排序
            int downsort[] = new int[temp.length];
            int index2 = temp.length - 1;
            //将排好序的数组按倒序方式赋给下一个新的数组
            for (int j = 0; j < downsort.length; j++) {
                downsort[j] = temp[index2--];
            }
            //输出新数组指定索引位置元素
            System.out.println(downsort[k - 1]);
        }
        sc.close();
    }

}

posted @ 2022-03-18 12:54  morning-start  阅读(55)  评论(0编辑  收藏  举报