• sweep line-The Skyline Problem


    2020-01-10 17:51:05

    问题描述

    问题求解

    本题是经典的sweep line问题。

    对于sweep line问题我们需要考虑的只有两点:

    1. 延水平方向 / 时间方向 :时间队列 event queue,一般来说是一个优先队列;

    2. 延垂直方向sweep line status,即当前的扫描线的状态,一般会将交点按照顺序排序;

    对于本题来说,sweep line status可以使用一个multi set来进行维护,当然由于在Java中没有multi set,因此需要使用TreeMap来模拟。

    event queue的当然是使用优先队列,问题是如何进行排序,这个才是本题的核心难点。

    这里给出结论:

    大方向是按照x轴排序,如果x轴相等那么按照height排序;

    如果x轴相等,优先判断是否是左端点,如果是左端点,那么优先入队;

    如果同时是右端点,那么需要反序入队,就是height小的反而需要排在前面。

        public List<List<Integer>> getSkyline(int[][] buildings) {
            List<List<Integer>> res = new ArrayList<>();
            // 对于同x轴,优先将左端点入队列
            // 如果同是右端点,则要反序,小的先入队列
            // 其余按照正常的height顺序排列即可
            PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>(){
                public int compare(int[] o1, int[] o2) {
                    if (o1[0] == o2[0] && o1[2] != o2[2]) return o1[2] - o2[2];
                    if (o1[0] == o2[0] && o1[2] == 1 && o1[2] == o2[2]) return o1[1] - o2[1];
                    return o1[0] == o2[0] ? o2[1] - o1[1] : o1[0] - o2[0];
                }
            });
            TreeMap<Integer, Integer> map = new TreeMap<>();
            for (int[] b : buildings) {
                int s = b[0];
                int e = b[1];
                int h = b[2];
                pq.add(new int[]{s, h, 0});
                pq.add(new int[]{e, h, 1});
            }
            while(!pq.isEmpty()) {
                int[] event = pq.poll();
                int x = event[0];
                int h = event[1];
                int status = event[2];         
                int curr_max = map.size() == 0 ? 0 : map.lastKey();
                if (status == 0) {
                    if (h > curr_max) res.add(Arrays.asList(x, h));
                    map.put(h, map.getOrDefault(h, 0) + 1);
                }
                else {
                    map.put(h, map.get(h) - 1);
                    if (map.get(h) == 0) map.remove(h);
                    curr_max = map.size() == 0 ? 0 : map.lastKey();
                    if (h > curr_max) res.add(Arrays.asList(x, curr_max));
                }
                
            }
            return res;
        }
    

      

  • 相关阅读:
    leetcode_24. 两两交换链表中的节点
    Mysql大数据量分页优化
    MySQL 默认排序是什么
    spring注入map,spring注入一个接口的多个实现类在map里
    eureka缓存细节以及生产环境的最佳配置
    MySQL 5.7性能调优
    安装后的十个MySQL性能调整设置(版本:5.1、5.5 和5.6)
    docker部署tomcat应用和MySQL数据库
    MySQL热备工具Xtrabackup
    MySQL数据库的冷备方式
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/12177474.html
Copyright © 2020-2023  润新知