牛客网2019笔试真题:牛牛找工作

题目地址:牛牛找工作

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        TreeMap<Integer,Integer> map = new TreeMap<>();//利用TreeMap的排序特性
        //所有测试用例都是一起给的,所以要while循环
        while(in.hasNext()) {
            map.clear();
            int n = in.nextInt();
            int m = in.nextInt();
            for(int i = 0;i < n;i++) {
                int d = in.nextInt();
                int p = in.nextInt();
                map.put(d,p);
            }
            int max = Integer.MIN_VALUE;
            for(Map.Entry<Integer,Integer> entry : map.entrySet()) {
            //以key为递增顺序的entry,选择出当前能力中最大的报酬,max为从低到高能力中最大的报酬
                if(entry.getValue() > max)
                    max = entry.getValue();
                else
                    map.put(entry.getKey(),max);
            }
            for(int i = 0;i < m;i++) {
                int cur = in.nextInt();
                //floorEntry()方法会返回一个小于等于当前key中所有key的最大值
                Map.Entry<Integer, Integer> result = map.floorEntry(cur);
                if(result == null)System.out.println(0);
                else System.out.println(result.getValue());
            }
        }
    }
}

扩展:
TreeMap特性之一是默认根据key进行升序排序,也可以根据自己定义的比较器comparator进行排序。
floorEntry(K Key)方法返回一个小于等于指定key中最接近(最大)的key,没有则返回null
lowerEntry(K key)方法返回一个小于指定key中最接近(最大)的key,没有则返回null
higherEntry(K key)方法返回一个大于指定key中最接近(最小)的key,没有则返回null

发布了352 篇原创文章 · 获赞 73 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43777983/article/details/105306707