LeetCode 题解工作台
收集足够苹果的最小花园周长
给你一个用无限二维网格表示的花园, 每一个 整数坐标处都有一棵苹果树。整数坐标 (i, j) 处的苹果树有 |i| + |j| 个苹果。 你将会买下正中心坐标是 (0, 0) 的一块 正方形土地 ,且每条边都与两条坐标轴之一平行。 给你一个整数 neededApples ,请你返回土地的 最小周长 …
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
假设正方形右上角坐标为 $(n, n)$,那么它的边长为 ,周长为 ,里面的苹果总数为: $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你一个用无限二维网格表示的花园,每一个 整数坐标处都有一棵苹果树。整数坐标 (i, j) 处的苹果树有 |i| + |j| 个苹果。
你将会买下正中心坐标是 (0, 0) 的一块 正方形土地 ,且每条边都与两条坐标轴之一平行。
给你一个整数 neededApples ,请你返回土地的 最小周长 ,使得 至少 有 neededApples 个苹果在土地 里面或者边缘上。
|x| 的值定义为:
- 如果
x >= 0,那么值为x - 如果
x < 0,那么值为-x
示例 1:
输入:neededApples = 1 输出:8 解释:边长长度为 1 的正方形不包含任何苹果。 但是边长为 2 的正方形包含 12 个苹果(如上图所示)。 周长为 2 * 4 = 8 。
示例 2:
输入:neededApples = 13 输出:16
示例 3:
输入:neededApples = 1000000000 输出:5040
提示:
1 <= neededApples <= 1015
解题思路
方法一:数学 + 枚举
假设正方形右上角坐标为 ,那么它的边长为 ,周长为 ,里面的苹果总数为:
由于 和 是对称的,所以可以化简为:
所以,我们只需要枚举 ,直到找到第一个满足 的 即可。
时间复杂度 ,其中 为 的值。空间复杂度 。
class Solution:
def minimumPerimeter(self, neededApples: int) -> int:
x = 1
while 2 * x * (x + 1) * (2 * x + 1) < neededApples:
x += 1
return x * 8
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate uses binary search effectively to minimize the number of checks needed to find the valid side length.
- question_mark
Candidate understands how to compute the apples inside the square using a formula.
- question_mark
Candidate knows how to calculate the perimeter after determining the side length of the square.
常见陷阱
外企场景- error
Candidate fails to correctly derive or use the formula for the number of apples inside a square.
- error
Candidate misuses binary search bounds, either searching too broadly or too narrowly.
- error
Candidate fails to properly compute the perimeter once the side length is determined.
进阶变体
外企场景- arrow_right_alt
Add additional constraints on the grid size or allowed range for neededApples.
- arrow_right_alt
Allow for different shapes of land (rectangular instead of square) and adjust the perimeter calculation.
- arrow_right_alt
Use this problem as a stepping stone to more complex grid-based problems involving multiple plots or obstacles.