LeetCode 题解工作台
两栋颜色不同且距离最远的房子
街上有 n 栋房子整齐地排成一列,每栋房子都粉刷上了漂亮的颜色。给你一个下标从 0 开始且长度为 n 的整数数组 colors ,其中 colors[i] 表示第 i 栋房子的颜色。 返回 两栋 颜色 不同 房子之间的 最大 距离。 第 i 栋房子和第 j 栋房子之间的距离是 abs(i - j) …
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 贪心·invariant
答案摘要
我们可以发现,如果第一栋房子和最后一栋房子颜色不同,那么它们之间的距离就是最大的距离,即 $n - 1$。 如果第一栋房子和最后一栋房子颜色相同,那么我们可以从左向右找到第一栋颜色不同的房子,记为 ,从右向左找到第一栋颜色不同的房子,记为 ,那么最大的距离就是 $\max(n - i - 1, j)$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
街上有 n 栋房子整齐地排成一列,每栋房子都粉刷上了漂亮的颜色。给你一个下标从 0 开始且长度为 n 的整数数组 colors ,其中 colors[i] 表示第 i 栋房子的颜色。
返回 两栋 颜色 不同 房子之间的 最大 距离。
第 i 栋房子和第 j 栋房子之间的距离是 abs(i - j) ,其中 abs(x) 是 x 的绝对值。
示例 1:

输入:colors = [1,1,1,6,1,1,1] 输出:3 解释:上图中,颜色 1 标识成蓝色,颜色 6 标识成红色。 两栋颜色不同且距离最远的房子是房子 0 和房子 3 。 房子 0 的颜色是颜色 1 ,房子 3 的颜色是颜色 6 。两栋房子之间的距离是 abs(0 - 3) = 3 。 注意,房子 3 和房子 6 也可以产生最佳答案。
示例 2:

输入:colors = [1,8,3,8,3] 输出:4 解释:上图中,颜色 1 标识成蓝色,颜色 8 标识成黄色,颜色 3 标识成绿色。 两栋颜色不同且距离最远的房子是房子 0 和房子 4 。 房子 0 的颜色是颜色 1 ,房子 4 的颜色是颜色 3 。两栋房子之间的距离是 abs(0 - 4) = 4 。
示例 3:
输入:colors = [0,1] 输出:1 解释:两栋颜色不同且距离最远的房子是房子 0 和房子 1 。 房子 0 的颜色是颜色 0 ,房子 1 的颜色是颜色 1 。两栋房子之间的距离是 abs(0 - 1) = 1 。
提示:
n == colors.length2 <= n <= 1000 <= colors[i] <= 100- 生成的测试数据满足 至少 存在 2 栋颜色不同的房子
解题思路
方法一:贪心
我们可以发现,如果第一栋房子和最后一栋房子颜色不同,那么它们之间的距离就是最大的距离,即 。
如果第一栋房子和最后一栋房子颜色相同,那么我们可以从左向右找到第一栋颜色不同的房子,记为 ,从右向左找到第一栋颜色不同的房子,记为 ,那么最大的距离就是 。
时间复杂度 ,其中 是房子的数量。空间复杂度 。
class Solution:
def maxDistance(self, colors: List[int]) -> int:
n = len(colors)
if colors[0] != colors[-1]:
return n - 1
i, j = 1, n - 2
while colors[i] == colors[0]:
i += 1
while colors[j] == colors[0]:
j -= 1
return max(n - i - 1, j)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Evaluate the candidate's understanding of greedy algorithms and invariant validation.
- question_mark
Check if the candidate recognizes the simplicity of the problem due to the small input size.
- question_mark
Test the candidate's ability to optimize the approach without unnecessary calculations.
常见陷阱
外企场景- error
Overcomplicating the solution by checking all possible house pairs rather than focusing on the first and last occurrences of different colors.
- error
Failing to correctly handle cases where the first and last houses with distinct colors are not at the extremes.
- error
Misunderstanding the constraints and trying inefficient solutions despite small input sizes.
进阶变体
外企场景- arrow_right_alt
What if the input size increased to 1000 or more? Consider adjusting the approach to handle larger inputs efficiently.
- arrow_right_alt
What if the problem asks for the smallest distance instead of the largest? Modify the greedy approach accordingly.
- arrow_right_alt
What if the colors array contains many duplicates? Ensure your solution still adheres to the pattern of maximizing the distance between different colors.