1333.餐厅过滤器

 题目描述:

class Solution {
    public List<Integer> filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) {

        List<Integer> list = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<>(); // key: 餐馆ID, value: 评分

        for (int[] restaurant : restaurants) {
            int id = restaurant[0];
            int rating = restaurant[1];
            int isVegan = restaurant[2];
            int price = restaurant[3];
            int distance = restaurant[4];

            // 修正条件判断
            boolean condition;
            if (veganFriendly == 1) {
                condition = (isVegan == 1) && (price <= maxPrice) && (distance <= maxDistance);
            } else {
                condition = (price <= maxPrice) && (distance <= maxDistance);
            }

            if (condition) {
                map.put(id, rating); // 用餐馆ID作为key
            }
        }

        // 转换为List并排序
        List<Map.Entry<Integer, Integer>> sorted = new ArrayList<>(map.entrySet());
        Collections.sort(sorted, (a, b) -> {
            int cmp = Integer.compare(b.getValue(), a.getValue());
            return (cmp != 0) ? cmp : Integer.compare(b.getKey(), a.getKey());
        });
        /*
        Collections.sort(sorted, (a, b) -> {
    // 比较两个条目的值
    if (b.getValue().equals(a.getValue())) {  
        // 值相同:按键降序(返回b的键 - a的键)
        return b.getKey() - a.getKey();
    } else {  
        // 值不同:按值降序(返回b的值 - a的值)
        return b.getValue() - a.getValue();
    }
});*/

        // 填充结果
        for (Map.Entry<Integer, Integer> entry : sorted) {
            list.add(entry.getKey());
        }

        return list;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XF鸭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值