题解 | 餐馆

餐馆

https://www.nowcoder.com/practice/d2cced737eb54a3aa550f53bb3cc19d0

二分,寻找每一次能匹配上的比较大的桌子,实际上这道题还能用最大堆做。

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();//n张桌子
        int m = sc.nextInt();//m批客人
        int[] table = new int[n];
        int[][] customers = new int[m][2];

        for (int i = 0; i < n; i++) {
            table[i] = sc.nextInt();
        }

        for (int i = 0; i < m; i++) {
            customers[i][0] = sc.nextInt();
            customers[i][1] = sc.nextInt();
        }
        
        Arrays.sort(customers, (a, b) -> b[1] - a[1]);
        Arrays.sort(table);

        long ans = 0L;
        int[] used = new int[n];

        for (int i = 0; i < m; i++) {
            if (table[n - 1] <
                    customers[i][0]) { 
                continue;
            }
            int num = customers[i][0];
            int price = customers[i][1];

            //找到合适的桌子坐
            int idx = binarySearch(num, table);
            while (idx < n && used[idx] == 1) {
                idx++;
            }
            if (idx < n) {
                ans += price;
                used[idx] = 1;
            }
        }
        System.out.println(ans);
    }

    //二分查找
    public static int binarySearch(int target, int[] table) {
        int l = -1;
        int r = table.length;
        while (l + 1 < r) {
            int mid = (l + r) >>> 1;
            if (table[mid] >= target) {
                r = mid;
            } else {
                l = mid;
            }
        }
        return r;
    }
}

全部评论

相关推荐

05-03 12:45
西南大学 Java
nsnzkv:你这项目写的内容太多了,说实话都是在给自己挖坑,就算简历过了,后面面试也难受
点赞 评论 收藏
分享
04-29 22:35
门头沟学院 Java
牛友说改了名字能收到offer:旧图新发查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务