蓝桥杯 算法训练 区间k大数查询


算法训练 区间k大数查询

Description

给定一个序列,每次询问序列中第l个数到第r个数中第K大的数是哪个。

Input

输入描述:

第一行包含一个数n,表示序列长度。

第二行包含n个正整数,表示给定的序列。

第三个包含一个正整数m,表示询问个数。

接下来m行,每行三个数l,r,K,表示询问序列从左往右第l个数到第r个数中,从大往小第K大的数是哪个。序列元素从1开始标号。

输入样例:

5

1 2 3 4 5

2

1 5 2

2 3 2

Output

输出描述:

总共输出m行,每行一个数,表示询问的答案。

输出样例:

4

2

HINT:时间限制:1.0s 内存限制:256.0MB

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

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

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

Source

蓝桥杯练习系统 ID: 11 原题链接: http://lx.lanqiao.cn/problem.page?gpid=T11

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scanner = new Scanner(System.in);
        //存储输出结果
        List<Integer> output = new ArrayList<Integer>();

        int n = scanner.nextInt();

        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < n; i++) {
            list.add(scanner.nextInt());
        }

        int m = scanner.nextInt();

        for (int i = 0; i < m; i++) {
            int I = scanner.nextInt()-1;
            int r = scanner.nextInt();
            int K = scanner.nextInt();
            //list.subList(fromIndex, toIndex)截取指定范围
            List<Integer> temp = new ArrayList<Integer>(list.subList(I, r));
            Collections.sort(temp,new Comparator<Integer>() {
                //降序排序
                @Override
                public int compare(Integer o1, Integer o2) {
                    // TODO Auto-generated method stub
                    return o2-o1;
                }
            });
            output.add(temp.get(K-1));
        }

        for (Integer res : output) {
            System.out.println(res);
        }

        scanner.close();
    }

}

Author: qwq小小舒
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source qwq小小舒 !
  TOC