zoukankan      html  css  js  c++  java
  • JAVA比较器的写法和优先队列的使用

    1333. Filter Restaurants by Vegan-Friendly, Price and Distance

    这道题做的过程中,由于语法不熟悉,花费了大量时间,需要掌握comparator自定义写法。

    本题可以

    1.用HashMap来存过滤后的数据,然后用自定义的比较器,在list中对符合要求的数据排序。

    2.用PriorityQueue,自定义优先队列的排序方式,将筛选后的数据存入优先队列,即可自动有序。

    class Solution {
        public List<Integer> filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) {
            Map<Integer, int[]> map = new HashMap<>();
            List<Integer> IDs = new ArrayList<>();
            for(int[] id : restaurants){
                if(id[2] >= veganFriendly && id[3] <= maxPrice && id[4] <= maxDistance){
                    map.put(id[0], id);
                    IDs.add(id[0]);
                }
            }
            //第一种写法
           /* Collections.sort(IDs, (id1, id2) -> {
                int rating1 = map.get(id1)[1];
                int rating2 = map.get(id2)[1];
                if(rating1 == rating2) return id2-id1;
                return rating2-rating1;
            });
            */
            //第二种写法
            IDs.sort(new Comparator<Integer>(){
                @Override
                public int compare(Integer o1, Integer o2){
                    int rating1 = map.get(o1)[1];
                    int rating2 = map.get(o2)[1];
                    if(rating1 == rating2) return o2-o1;
                    return rating2-rating1;
                }
            });
            return IDs;
        }
    }
    class Solution {
        public List<Integer> filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) {
          //PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> b[1] == a[1]? b[0] - a[0]: b[1]-a[1])
            PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>(){
                @Override
                public int compare(int[] o1, int[] o2){
                    if(o1[1] == o2[1]) return o2[0]-o1[0];
                    return o2[1]-o1[1];
                }
            });
            List<Integer> res = new ArrayList<>();
            for(int[] id : restaurants){
                if(id[2] >= veganFriendly && id[3] <= maxPrice && id[4] <= maxDistance)
                    pq.add(id);
            }
            while(!pq.isEmpty()) 
                res.add(pq.remove()[0]);
            return res;
        }
    }
  • 相关阅读:
    Delphi XE5 android 蓝牙通讯传输
    Delphi XE5 android toast
    Delphi XE5 android openurl(转)
    Delphi XE5 如何设计并使用FireMonkeyStyle(转)
    Delphi XE5 android 捕获几个事件
    Delphi XE5 android listview
    Delphi XE5 android 黑屏的临时解决办法
    Delphi XE5 android popumenu
    Delphi XE5 android 获取网络状态
    Delphi XE5 android 获取电池电量
  • 原文地址:https://www.cnblogs.com/yawenw/p/13021519.html
Copyright © 2011-2022 走看看