Given the following 2D Bounding Box struct, write a function to merge n bounding boxes together, and return a final bounding box with the result.
struct BBox {
float x; // x position of the box center.
float y; // y position of the box center.
float w; // width of the box (x direction).
float h; // height of the box (y direction).
};
BBox merge(BBox *boxes, int boxCount)
{}
这道题的核心是把多个以“中心点 + 宽高”表示的二维矩形框,合并成一个能够覆盖所有输入框的最终边界框。常见做法是先遍历所有盒子,分别计算每个框的左右上下边界,再取所有框的最小左边界、最大右边界、最小下边界和最大上边界,最后反推出合并后的中心点、宽度和高度。题目本质上考察的是几何边界转换与线性扫描,时间复杂度通常是 O(n),实现时要注意坐标系和宽高的定义方向。
正文完