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;
        }
    }
  • 相关阅读:
    vmware 安装提示the msi failed
    答辩修改记录
    科研系统修改记录
    python2.7学习记录之四
    sql语句--查询语句(MySQL)
    lei muban
    共模与差模的区别是什么?
    linux pinmux 引脚多路复用驱动分析与使用
    纯虚函数
    内核与驱动文件的version magic匹配问题
  • 原文地址:https://www.cnblogs.com/yawenw/p/13021519.html
Copyright © 2011-2022 走看看