1. 程式人生 > 資訊 >【IT黑板報 vol.33圖文版】小米平板 5 提前用上Android 12,摺疊屏 OPPO Find N “無”摺痕

【IT黑板報 vol.33圖文版】小米平板 5 提前用上Android 12,摺疊屏 OPPO Find N “無”摺痕

城市的天際線是從遠處觀看該城市中所有建築物形成的輪廓的外部輪廓。給你所有建築物的位置和高度,請返回由這些建築物形成的 天際線 。

每個建築物的幾何資訊由陣列 buildings 表示,其中三元組 buildings[i] = [lefti, righti, heighti] 表示:

lefti 是第 i 座建築物左邊緣的 x 座標。
righti 是第 i 座建築物右邊緣的 x 座標。
heighti 是第 i 座建築物的高度。
天際線 應該表示為由 “關鍵點” 組成的列表,格式 [[x1,y1],[x2,y2],...] ,並按 x 座標 進行 排序 。關鍵點是水平線段的左端點。列表中最後一個點是最右側建築物的終點,y 座標始終為 0 ,僅用於標記天際線的終點。此外,任何兩個相鄰建築物之間的地面都應被視為天際線輪廓的一部分。

注意:輸出天際線中不得有連續的相同高度的水平線。例如 [...[2 3], [4 5], [7 5], [11 5], [12 7]...] 是不正確的答案;三條高度為 5 的線應該在最終輸出中合併為一個:[...[2 3], [4 5], [12 7], ...]

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/the-skyline-problem
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

有序表

import java.util.*;

class Solution {
    public List<List<Integer>> getSkyline(int[][] buildings) {
        if (buildings == null || buildings.length == 0 || buildings[0].length == 0) {
            return Collections.emptyList();
        }

        Operation[] operations = new Operation[buildings.length * 2];

        for (int i = 0; i < buildings.length; ++i) {
            operations[i * 2] = new Operation(buildings[i][0], buildings[i][2]);
            operations[i * 2 + 1] = new Operation(buildings[i][1], -buildings[i][2]);
        }

        Arrays.sort(operations, new Comparator<Operation>() {

            @Override
            public int compare(Operation o1, Operation o2) {
                if (o1.coordinate == o2.coordinate) {
                    return Integer.compare(o2.change, o1.change);
                } else {
                    return Integer.compare(o1.coordinate, o2.coordinate);
                }
            }
        });

        List<List<Integer>> ret = new ArrayList<>();
        int preHeight = 0;

        TreeMap<Integer, Integer> heightTimesMap = new TreeMap<>();

        for (int i = 0; i < operations.length; ++i) {
            Integer times = heightTimesMap.getOrDefault(Math.abs(operations[i].change), 0);
            if (operations[i].change >= 0) {
                heightTimesMap.put(operations[i].change, times + 1);
            } else {
                if (times == 1) {
                    heightTimesMap.remove(-operations[i].change);
                } else {
                    heightTimesMap.put(-operations[i].change, times - 1);
                }
            }
            int curMaxHeight = heightTimesMap.isEmpty() ? 0 : heightTimesMap.lastKey();
            if (curMaxHeight != preHeight) {
                ret.add(Arrays.asList(operations[i].coordinate, curMaxHeight));
                preHeight = curMaxHeight;
            }
        }
        return ret;
    }
}

class Operation {
    int coordinate;
    int change;

    public Operation(int coordinate, int change) {
        this.coordinate = coordinate;
        this.change = change;
    }
}

優先佇列


心之所向,素履以往 生如逆旅,一葦以航