平分正方形(LeetCode 面试题 16.13):用"中心连线"求解二等分直线
平分正方形(LeetCode 面试题 16.13):用"中心连线"求解二等分直线
本文基于开源仓库 doocs/leetcode 中《程序员面试金典(第 6 版)》系列的 面试题 16.13 平分正方形 英文原题文档 README_EN.md 展开,系统讲解"找到一条同时把两个正方形二等分的直线"这一经典几何问题的数学原理、分类讨论算法,以及 Python / Java / C++ / Go / TypeScript / Swift 六种语言的完整实现与易错点。读完本文,你将掌握"任意过中心的直线平分正方形"这一几何引理,并能独立推导出求交点、排序端点、处理无穷斜率等一系列细节。
一、题目回顾:输入、输出与约束
原题 Bisect Squares 的设定非常简洁:
- 二维平面上有两个正方形,且正方形的顶边、底边都与 x 轴平行。
- 每个正方形用一个长度为 3 的数组表示:
[X, Y, side],其中[X, Y]是正方形左下角的坐标,side是边长。 - 需要找一条直线,把两个正方形同时切成面积相等的两半。
- 该直线穿过两个正方形会形成 4 个交点;请返回这 4 个交点中距离最远的两点(即线段能覆盖另外两个交点的两个端点)
[X1, Y1]与[X2, Y2],返回格式为{X1, Y1, X2, Y2}。
输出有两个排序约束,必须严格遵守:
- 若
X1 != X2,则要求X1 < X2(左端点在前); - 若
X1 == X2(竖直线段),则要求Y1 <= Y2(下端点在前)。
此外还有一个"多解"规则:若同时有多条直线满足要求,返回斜率最大的一条;与 y 轴平行的直线视为斜率无穷大。
题目给出的提示只有两条:square.length == 3、square[2] > 0,即数组必为 3 元素、边长必为正。
示例:
square1 = {-1, -1, 2}
square2 = {0, -1, 2}
输出:{-1, 0, 2, 0}
解释:y = 0 这条水平线能同时把两个正方形切成等面积两半,返回的两个端点为 [-1,0] 和 [2,0]
二、核心几何引理:平分正方形的直线必过正方形中心
这是整个问题的解题钥匙,也是文档 README_EN.md 中 "Solution 1: Geometric Mathematics" 一节的出发点:
若一条直线把一个正方形切成面积相等的两半,则该直线必过正方形中心。
正方形是中心对称图形,任意过其中心点的直线都会把它切成两个全等的部分(面积各为一半);反之,任何能平分正方形面积的直线也必然经过中心。因此,能同时平分两个正方形的直线,必然同时经过两个正方形的中心点。
于是问题被转化为:求经过两个中心点的直线,并计算它与两个正方形外包络矩形的交点。这一转化把"两条直线 + 四个交点"的搜索问题,变成了一次确定性计算。
设两个正方形的中心分别为 和 ,由左下角坐标加半边长即可得到:
在仓库的 Solution.py 中,这一步对应的正是开头三行:
x1, y1 = square1[0] + square1[2] / 2, square1[1] + square1[2] / 2
x2, y2 = square2[0] + square2[2] / 2, square2[1] + square2[2] / 2
三、分类讨论:竖直直线、陡峭直线与平缓直线
得到中心点之后,直线方程有两种形态,需要分类处理。这里"以斜率的绝对值大小分类"是整个算法最精妙的部分,原因在于:正方形的边是轴对齐的(axis-aligned),直线与哪组边相交取决于它的陡峭程度。
3.1 特殊情况:竖直平分线()
当两个正方形中心横坐标相等()时,经过两中心的直线垂直于 x 轴,斜率为无穷大。此时无需(也无法)计算斜率,直接求上下边界即可:
- 下端点纵坐标取两个正方形底边的最小值:
- 上端点纵坐标取两个正方形顶边的最大值:
Python 实现:
if x1 == x2:
y3 = min(square1[1], square2[1])
y4 = max(square1[1] + square1[2], square2[1] + square2[2])
return [x1, y3, x2, y4]
这个分支还隐藏着一个关键设计:它天然满足了"选择斜率最大的一条"的题意。当两个正方形中心完全重合( 且 )时,过该中心有无数条平分线,此时斜率最大的正是竖直直线(斜率视为无穷大),代码直接返回竖直情形正是对这一规则的落实。
3.2 一般情形:由两点确定直线
当 时,直线斜率为:
Python 实现:
k = (y2 - y1) / (x2 - x1)
b = y1 - k * x1
接下来按 与 1 的大小关系分成两种相交情形。
3.3 情形一:,直线与上下边相交
当直线足够"陡"(斜率绝对值大于 1)时,它穿出正方形的点是上下两条水平边,而不是左右两条竖直边。算法做法是:
- 以两个正方形底边纵坐标的最小值作为 :;
- 以两个正方形顶边纵坐标的最大值作为 :;
- 由直线方程反解横坐标:,得到 与 。
Python 实现:
if abs(k) > 1:
y3 = min(square1[1], square2[1])
x3 = (y3 - b) / k
y4 = max(square1[1] + square1[2], square2[1] + square2[2])
x4 = (y4 - b) / k
if x3 > x4 or (x3 == x4 and y3 > y4):
x3, y3, x4, y4 = x4, y4, x3, y3
注意最后三行:求出端点后按题意排序,若左端点比右端点靠右(),或横坐标相同但纵坐标更大( 且 ),则交换两端,保证输出满足 X1 < X2(或 X1 == X2 时 Y1 <= Y2)。
3.4 情形二:,直线与左右边相交
当直线较"平缓"时,它穿出正方形的是左右两条竖直边。对称地处理:
- 以两个正方形左边横坐标的最小值作为 :;
- 以两个正方形右边横坐标的最大值作为 :;
- 由直线方程直接求纵坐标:。
Python 实现:
else:
x3 = min(square1[0], square2[0])
y3 = k * x3 + b
x4 = max(square1[0] + square1[2], square2[0] + square2[2])
y4 = k * x4 + b
return [x3, y3, x4, y4]
该分支下必有 (两个左边/右边的最小值与最大值天然有序),因此无需交换。
四、为什么按 与 1 的关系分类?
这个分类不是凭空设定的,而是由"正方形四边与坐标轴平行"这一前提决定的:
- 当 时,直线在竖直方向上的"前进速度"快于水平方向。从正方形内部出发沿直线前进,必然先碰到上下两条水平边,因此交点取在
min(底边)与max(顶边)上; - 当 时,水平方向前进更快,必然先碰到左右两条竖直边,因此交点取在
min(左边)与max(右边)上; - 若以"错误的组"求交点(比如陡峭直线却去取左右边),求出的点会落在正方形的外部延长线上,导致答案错误。这正是文档中 "When ... otherwise ..." 两段说明的本质原因。
理解了这一点,就不难把算法推广到任意轴对齐矩形(长方形)的情形——只需把 square[i][2] 从"边长"推广为"宽/高"即可。
五、六种语言的完整实现对照
仓库在 lcci/16.13.Bisect%20Squares/ 目录下为每种语言提供了独立的 Solution 文件,与文档中的代码一一对应。这里逐一给出并说明各语言的实现细节。
5.1 Python(Solution.py)
class Solution:
def cutSquares(self, square1: List[int], square2: List[int]) -> List[float]:
x1, y1 = square1[0] + square1[2] / 2, square1[1] + square1[2] / 2
x2, y2 = square2[0] + square2[2] / 2, square2[1] + square2[2] / 2
if x1 == x2:
y3 = min(square1[1], square2[1])
y4 = max(square1[1] + square1[2], square2[1] + square2[2])
return [x1, y3, x2, y4]
k = (y2 - y1) / (x2 - x1)
b = y1 - k * x1
if abs(k) > 1:
y3 = min(square1[1], square2[1])
x3 = (y3 - b) / k
y4 = max(square1[1] + square1[2], square2[1] + square2[2])
x4 = (y4 - b) / k
if x3 > x4 or (x3 == x4 and y3 > y4):
x3, y3, x4, y4 = x4, y4, x3, y3
else:
x3 = min(square1[0], square2[0])
y3 = k * x3 + b
x4 = max(square1[0] + square1[2], square2[0] + square2[2])
y4 = k * x4 + b
return [x3, y3, x4, y4]
要点:Python 的除法 / 天然产生浮点数,因此 square1[2] / 2 无需显式转换类型。
5.2 Java(Solution.java)
class Solution {
public double[] cutSquares(int[] square1, int[] square2) {
double x1 = square1[0] + square1[2] / 2.0;
double y1 = square1[1] + square1[2] / 2.0;
double x2 = square2[0] + square2[2] / 2.0;
double y2 = square2[1] + square2[2] / 2.0;
if (x1 == x2) {
double y3 = Math.min(square1[1], square2[1]);
double y4 = Math.max(square1[1] + square1[2], square2[1] + square2[2]);
return new double[] {x1, y3, x2, y4};
}
double k = (y2 - y1) / (x2 - x1);
double b = y1 - k * x1;
if (Math.abs(k) > 1) {
double y3 = Math.min(square1[1], square2[1]);
double x3 = (y3 - b) / k;
double y4 = Math.max(square1[1] + square1[2], square2[1] + square2[2]);
double x4 = (y4 - b) / k;
if (x3 > x4 || (x3 == x4 && y3 > y4)) {
return new double[] {x4, y4, x3, y3};
}
return new double[] {x3, y3, x4, y4};
} else {
double x3 = Math.min(square1[0], square2[0]);
double y3 = k * x3 + b;
double x4 = Math.max(square1[0] + square1[2], square2[0] + square2[2]);
double y4 = k * x4 + b;
return new double[] {x3, y3, x4, y4};
}
}
}
要点:Java 中 int / int 是整除,必须写成 square1[2] / 2.0 才能得到浮点结果;交换端点时直接构造新的数组返回,避免引入临时变量。
5.3 C++(Solution.cpp)
class Solution {
public:
vector<double> cutSquares(vector<int>& square1, vector<int>& square2) {
double x1 = square1[0] + square1[2] / 2.0;
double y1 = square1[1] + square1[2] / 2.0;
double x2 = square2[0] + square2[2] / 2.0;
double y2 = square2[1] + square2[2] / 2.0;
if (x1 == x2) {
double y3 = min(square1[1], square2[1]);
double y4 = max(square1[1] + square1[2], square2[1] + square2[2]);
return {x1, y3, x2, y4};
}
double k = (y2 - y1) / (x2 - x1);
double b = y1 - k * x1;
if (abs(k) > 1) {
double y3 = min(square1[1], square2[1]);
double x3 = (y3 - b) / k;
double y4 = max(square1[1] + square1[2], square2[1] + square2[2]);
double x4 = (y4 - b) / k;
if (x3 > x4 || (x3 == x4 && y3 > y4)) {
return {x4, y4, x3, y3};
}
return {x3, y3, x4, y4};
} else {
double x3 = min(square1[0], square2[0]);
double y3 = k * x3 + b;
double x4 = max(square1[0] + square1[2], square2[0] + square2[2]);
double y4 = k * x4 + b;
return {x3, y3, x4, y4};
}
}
};
要点:与 Java 相同,square1[2] / 2.0 保证浮点除法;min / max 直接使用标准库的模板函数(此处参数均为 int,返回 int,赋给 double 时隐式转换)。
5.4 Go(Solution.go)
func cutSquares(square1 []int, square2 []int) []float64 {
x1, y1 := float64(square1[0])+float64(square1[2])/2, float64(square1[1])+float64(square1[2])/2
x2, y2 := float64(square2[0])+float64(square2[2])/2, float64(square2[1])+float64(square2[2])/2
if x1 == x2 {
y3 := math.Min(float64(square1[1]), float64(square2[1]))
y4 := math.Max(float64(square1[1]+square1[2]), float64(square2[1]+square2[2]))
return []float64{x1, y3, x2, y4}
}
k := (y2 - y1) / (x2 - x1)
b := y1 - k*x1
if math.Abs(k) > 1 {
y3 := math.Min(float64(square1[1]), float64(square2[1]))
x3 := (y3 - b) / k
y4 := math.Max(float64(square1[1]+square1[2]), float64(square2[1]+square2[2]))
x4 := (y4 - b) / k
if x3 > x4 || (x3 == x4 && y3 > y4) {
return []float64{x4, y4, x3, y3}
}
return []float64{x3, y3, x4, y4}
} else {
x3 := math.Min(float64(square1[0]), float64(square2[0]))
y3 := k*x3 + b
x4 := math.Max(float64(square1[0]+square1[2]), float64(square2[0]+square2[2]))
y4 := k*x4 + b
return []float64{x3, y3, x4, y4}
}
}
要点:Go 没有隐式类型转换,所有 int 参与浮点运算前都必须显式 float64(...) 包装;math.Min / math.Max / math.Abs 均要求 float64 参数。
5.5 TypeScript(Solution.ts)
function cutSquares(square1: number[], square2: number[]): number[] {
const x1 = square1[0] + square1[2] / 2;
const y1 = square1[1] + square1[2] / 2;
const x2 = square2[0] + square2[2] / 2;
const y2 = square2[1] + square2[2] / 2;
if (x1 === x2) {
const y3 = Math.min(square1[1], square2[1]);
const y4 = Math.max(square1[1] + square1[2], square2[1] + square2[2]);
return [x1, y3, x2, y4];
}
const k = (y2 - y1) / (x2 - x1);
const b = y1 - k * x1;
if (Math.abs(k) > 1) {
const y3 = Math.min(square1[1], square2[1]);
const x3 = (y3 - b) / k;
const y4 = Math.max(square1[1] + square1[2], square2[1] + square2[2]);
const x4 = (y4 - b) / k;
if (x3 > x4 || (x3 === x4 && y3 > y4)) {
return [x4, y4, x3, y3];
}
return [x3, y3, x4, y4];
} else {
const x3 = Math.min(square1[0], square2[0]);
const y3 = k * x3 + b;
const x4 = Math.max(square1[0] + square1[2], square2[0] + square2[2]);
const y4 = k * x4 + b;
return [x3, y3, x4, y4];
}
}
要点:TypeScript 的 number[] 与 JS 运行时一致,除法自动产生浮点数,逻辑与 Python 版本几乎逐行对应;比较时使用严格相等 ===。
5.6 Swift(Solution.swift)
class Solution {
func cutSquares(_ square1: [Int], _ square2: [Int]) -> [Double] {
let x1 = Double(square1[0]) + Double(square1[2]) / 2.0
let y1 = Double(square1[1]) + Double(square1[2]) / 2.0
let x2 = Double(square2[0]) + Double(square2[2]) / 2.0
let y2 = Double(square2[1]) + Double(square2[2]) / 2.0
if x1 == x2 {
let y3 = min(Double(square1[1]), Double(square2[1]))
let y4 = max(Double(square1[1]) + Double(square1[2]), Double(square2[1]) + Double(square2[2]))
return [x1, y3, x2, y4]
}
let k = (y2 - y1) / (x2 - x1)
let b = y1 - k * x1
if abs(k) > 1 {
let y3 = min(Double(square1[1]), Double(square2[1]))
let x3 = (y3 - b) / k
let y4 = max(Double(square1[1]) + Double(square1[2]), Double(square2[1]) + Double(square2[2]))
let x4 = (y4 - b) / k
if x3 > x4 || (x3 == x4 && y3 > y4) {
return [x4, y4, x3, y3]
}
return [x3, y3, x4, y4]
} else {
let x3 = min(Double(square1[0]), Double(square2[0]))
let y3 = k * x3 + b
let x4 = max(Double(square1[0]) + Double(square1[2]), Double(square2[0]) + Double(square2[2]))
let y4 = k * x4 + b
return [x3, y3, x4, y4]
}
}
}
要点:Swift 中 Int 与 Double 之间同样需要显式转换;min / max 直接使用全局函数。
可以看到,六种语言的核心算法结构完全一致,差异只在于类型转换与标准库调用方式。这正是 doocs/leetcode 仓库"同一题解、多语言覆盖"组织方式的体现。
六、复杂度与边界条件分析
6.1 时间复杂度
算法全程只做常数次四则运算、min / max 比较与一次可能的交换,时间复杂度为 ,空间复杂度为 ,不依赖输入规模(输入固定为两个长度为 3 的数组)。
6.2 必须覆盖的边界条件
| 边界情形 | 处理方式 | 代码位置(以 Python 为例) |
|---|---|---|
| 两中心横坐标相同(含中心重合) | 走竖直分支,直接比较底边/顶边,返回竖直线段 | if x1 == x2: 分支 |
| 中心完全重合(无限多条平分线) | 竖直直线斜率视为无穷大,满足"选斜率最大"要求 | 同上,x1 == x2 即覆盖 |
| $ | k | > 1$(陡峭直线) |
| $ | k | \le 1$(平缓直线) |
| 交换后端点排序 | 保证 X1 < X2,或 X1 == X2 时 Y1 <= Y2 |
if x3 > x4 or (x3 == x4 and y3 > y4): |
6.3 浮点比较的一个隐蔽细节
代码中用 if x1 == x2 判断中心横坐标是否相等。由于输入 square[0] 与 square[2] 都是整数,而 x = square[0] + square[2] / 2.0 是两个整数参与运算的结果(形如 整数 + 0.5 的倍数),这类数值在二进制浮点中通常是精确可表示的,因此直接判等在实际测试用例下是安全的。若输入可能为任意浮点数,更稳妥的做法是改用极小阈值(如 abs(x1 - x2) < 1e-9)比较——从工程稳健性角度,这是一个值得注意的扩展点。
七、扩展思考:从正方形推广到矩形
原题限定"正方形且边与坐标轴平行",但本文的算法稍作推广即可处理更一般的轴对齐矩形:
- 中心坐标公式不变:
center = (left + width/2, bottom + height/2); - 相交边界的判断依然以斜率绝对值与 1 的关系为准(矩形仍是轴对齐的);
- 只需把
square[2]替换为矩形的高,把"左边/右边"替换为矩形的左右边界即可。
这也解释了为什么该题在 lcci/README.md 中被归类为 几何 标签、难度为中等——它考察的并非复杂的数据结构,而是对几何性质(中心对称)与分类讨论能力的综合运用。
八、小结
面试题 16.13「平分正方形」是一道典型的"几何性质 + 分类讨论"题目,核心解题链路可以概括为:
- 化简:能平分正方形的直线必过其中心,问题转化为"过两中心点的直线与外包络矩形的交点";
- 分类:竖直情形()单独处理,天然满足"斜率最大"的题意;一般情形按 与 1 的关系决定取上下边还是左右边;
- 排序:对端点按要求排序,保证输出
X1 < X2(或竖直时Y1 <= Y2); - 复杂度:全程 时间、 空间的常数级几何运算。
仓库中该题的完整资源包括:中文题解 README.md、英文题解 README_EN.md,以及 Solution.py、Solution.java、Solution.cpp、Solution.go、Solution.ts、Solution.swift 六份单语言实现,均可直接阅读或复制运行。如果你想在同一系列中继续练习几何类题目,可以浏览 lcci 系列题解目录 快速检索更多题目。