LeetCode //C - 218. The Skyline Problem

时间:2024-07-11 10:24:09

218. The Skyline Problem

A city’s skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively.

The geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]:

lefti is the x coordinate of the left edge of the ith building.
righti is the x coordinate of the right edge of the ith building.
heighti is the height of the ith building.
You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.

The skyline should be represented as a list of “key points” sorted by their x-coordinate in the form [[x1,y1],[x2,y2],…]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline’s termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline’s contour.

Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, […,[2 3],[4 5],[7 5],[11 5],[12 7],…] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: […,[2 3],[4 5],[12 7],…]
 

Example 1:

在这里插入图片描述

Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]
Explanation:
Figure A shows the buildings of the input.
Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.

Example 2:

Input: buildings = [[0,2,3],[2,5,3]]
Output: [[0,3],[5,0]]

Constraints:
  • 1 < = b u i l d i n g s . l e n g t h < = 10 f 4 1 <= buildings.length <= 10f^4 1<=buildings.length<=10f4
  • 0 < = l e f t i < r i g h t i < = 2 31 − 1 0 <= lefti < righti <= 2^{31} - 1 0<=lefti<righti<=2311
  • 1 < = h e i g h t i < = 2 31 − 1 1 <= heighti <= 2^{31} - 1 1<=heighti<=2311
  • buildings is sorted by lefti in non-decreasing order.

From: LeetCode
Link: 218. The Skyline Problem


Solution:

Ideas:
  1. Representation of Building Edges:
  • Each building is represented by its left and right edges along with its height.
  • These edges are stored in an array where each edge is either a start (left edge) or end (right edge).
  1. Sorting of Edges:
  • All edges are sorted by their x-coordinate.
  • If two edges have the same x-coordinate, the start edge is processed before the end edge. If two start edges or two end edges have the same x-coordinate, the one with the greater height is processed first.
  1. Using a Max-Heap to Track Heights:
  • A max-heap is used to keep track of the current active building heights.
  • When processing a start edge, the height is added to the heap.
  • When processing an end edge, the height is removed from the heap.
  • The max-heap allows us to efficiently get the current highest building at any point.
  1. Generating the Skyline:
  • As we process each edge, we check the current maximum height in the heap.
  • If the current maximum height changes compared to the previous maximum height, it means there is a key point in the skyline.
  • This key point (x-coordinate and new height) is added to the result.
Code:
/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
// Data structure to store building edges
typedef struct {
    int x, height, isStart;
} Edge;

// Comparator for sorting edges
int compareEdges(const void* a, const void* b) {
    Edge* edgeA = (Edge*)a;
    Edge* edgeB = (Edge*)b;
    if (edgeA->x != edgeB->x) return edgeA->x - edgeB->x;
    // If two edges have the same x value, we need to process the start edge before the end edge
    if (edgeA->isStart != edgeB->isStart) return edgeB->isStart - edgeA->isStart;
    return edgeA->isStart ? (edgeB->height - edgeA->height) : (edgeA->height - edgeB->height);
}

// Max Heap Data Structure
typedef struct {
    int* heights;
    int size;
    int capacity;
} MaxHeap;

MaxHeap* createMaxHeap(int capacity) {
    MaxHeap* heap = (MaxHeap*)malloc(sizeof(MaxHeap));
    heap->heights = (int*)malloc(sizeof(int) * capacity);
    heap->size = 0;
    heap->capacity = capacity;
    return heap;
}

void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void maxHeapify(MaxHeap* heap, int idx) {
    int largest = idx;
    int left = 2 * idx + 1;
    int right = 2 * idx + 2;
    if (left < heap->size && heap->heights[left] > heap->heights[largest]) largest = left;
    if (right < heap->size && heap->heights[right] > heap->heights[largest]) largest = right;
    if (largest != idx) {
        swap(&heap->heights[largest], &heap->heights[idx]);
        maxHeapify(heap, largest);
    }
}

void insertMaxHeap(MaxHeap* heap, int height) {
    heap->heights[heap->size] = height;
    int i = heap->size;
    heap->size++;
    while (i != 0 && heap->heights[(i - 1) / 2] < heap->heights[i]) {
        swap(&heap->heights[(i - 1) / 2], &heap->heights[i]);
        i = (i - 1) / 2;
    }
}

void removeMaxHeap(MaxHeap* heap, int height) {
    int i;
    for (i = 0; i < heap->size; ++i) {
        if (heap->heights[i] == height) break;
    }
    if (i == heap->size) return;
    heap->heights[i] = heap->heights[heap->size - 1];
    heap->size--;
    maxHeapify(heap, i);
}

int getMaxHeap(MaxHeap* heap) {
    return heap->size == 0 ? 0 : heap->heights[0];
}

// Function to get the skyline
int** getSkyline(int** buildings, int buildingsSize, int* buildingsColSize, int* returnSize, int** returnColumnSizes) {
    if (buildingsSize == 0) {
        *returnSize = 0;
        return NULL;
    }
    
    Edge* edges = (Edge*)malloc(sizeof(Edge) * buildingsSize * 2);
    int edgeCount = 0;
    
    // Create edges
    for (int i = 0; i < buildingsSize; ++i) {
        edges[edgeCount++] = (Edge){buildings[i][0], buildings[i][2], 1};  // start edge
        edges[edgeCount++] = (Edge){buildings[i][1], buildings[i][2], 0};  // end edge
    }
    
    // Sort edges
    qsort(edges, edgeCount, sizeof(Edge), compareEdges);
    
    MaxHeap* heap = createMaxHeap(edgeCount);
    int** result = (int**)malloc(sizeof(int*) * edgeCount);
    *returnColumnSizes = (int*)malloc(sizeof(int) * edgeCount);
    *returnSize = 0;
    
    int prevMaxHeight = 0;
    for (int i = 0; i < edgeCount; ++i) {
        if (edges[i].isStart) {
            insertMaxHeap(heap, edges[i].height);
        } else {
            removeMaxHeap(heap, edges[i].height);
        }
        
        int currentMaxHeight = getMaxHeap(heap);
        if (currentMaxHeight != prevMaxHeight) {
            result[*returnSize] = (int*)malloc(sizeof(int) * 2);
            result[*returnSize][0] = edges[i].x;
            result[*returnSize][1] = currentMaxHeight;
            (*returnColumnSizes)[*returnSize] = 2;
            (*returnSize)++;
            prevMaxHeight = currentMaxHeight;
        }
    }
    
    free(edges);
    free(heap->heights);
    free(heap);
    
    return result;
}