牛客網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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章