218. The Skyline Problem (最大堆)

来源:互联网 发布:ubuntu自带gcc编译器 编辑:程序博客网 时间:2024/06/05 06:57

题意:

给你一堆建筑的左右边界和高度,让你求其映射到坐标系后,所有有效的拐点(详情看原题)

思路:

用线性表维护每个建筑的左右边界坐标,按横坐标升序排序后遍历,遍历时用最大堆维护某横坐标上存在的高度,pre记录未处理当前点时可选的最大高度,cur记录处理完当前点后可选的最大高度。如果pre!=cur说明存在有效拐点

java代码:

class Solution {    public List<int[]> getSkyline(int[][] buildings) {        List<int[]> list = new ArrayList<int[]>();        //java下最大堆的定义方法。        PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(11,            new Comparator<Integer>() {                public int compare(Integer a, Integer b) {                    return b - a;                }            });        List<int[]> arr = new ArrayList<int[]>();        for(int i = 0;i<buildings.length;i++){            arr.add(new int[]{buildings[i][0],buildings[i][2]});            arr.add(new int[]{buildings[i][1],-buildings[i][2]});        }        //java下快速排序的定义方法。        Collections.sort(arr, new Comparator<int[]>() {        public int compare(int[] a, int[] b) {            return a[0] == b[0] ? b[1] - a[1] : a[0] - b[0];        }        });        int cur = 0,pre = 0;        maxHeap.add(0);        for(int i = 0;i<arr.size();i++){            int temp[] = arr.get(i);            if(temp[1]>0){                maxHeap.add(temp[1]);                cur = maxHeap.peek();            }            else{                maxHeap.remove(-temp[1]);                cur =  maxHeap.peek();            }            if(pre!=cur){                list.add(new int[]{temp[0],cur});                pre = cur;            }        }        return list;    }}

原创粉丝点击