LeetCode 题解工作台

放置盒子

有一个立方体房间,其长度、宽度和高度都等于 n 个单位。请你在房间里放置 n 个盒子,每个盒子都是一个单位边长的立方体。放置规则如下: 你可以把盒子放在地板上的任何地方。 如果盒子 x 需要放置在盒子 y 的顶部,那么盒子 y 竖直的四个侧面都 必须 与另一个盒子或墙相邻。 给你一个整数 n ,返回…

category

3

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

困难 · 二分·搜索·答案·空间

bolt

答案摘要

根据题目描述,层数最高的盒子需要放在墙角,并且盒子的摆放呈阶梯状,这样可以使得接触地面的盒子数量最少。 假设盒子摆放 层,从上到下,每一层如果摆满,那么个数分别是 $1, 1+2, 1+2+3, \cdots, 1+2+\cdots+k$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

有一个立方体房间,其长度、宽度和高度都等于 n 个单位。请你在房间里放置 n 个盒子,每个盒子都是一个单位边长的立方体。放置规则如下:

  • 你可以把盒子放在地板上的任何地方。
  • 如果盒子 x 需要放置在盒子 y 的顶部,那么盒子 y 竖直的四个侧面都 必须 与另一个盒子或墙相邻。

给你一个整数 n ,返回接触地面的盒子的 最少 可能数量

 

示例 1:

输入:n = 3
输出:3
解释:上图是 3 个盒子的摆放位置。
这些盒子放在房间的一角,对应左侧位置。

示例 2:

输入:n = 4
输出:3
解释:上图是 3 个盒子的摆放位置。
这些盒子放在房间的一角,对应左侧位置。

示例 3:

输入:n = 10
输出:6
解释:上图是 10 个盒子的摆放位置。
这些盒子放在房间的一角,对应后方位置。

 

提示:

  • 1 <= n <= 109
lightbulb

解题思路

方法一:数学规律

根据题目描述,层数最高的盒子需要放在墙角,并且盒子的摆放呈阶梯状,这样可以使得接触地面的盒子数量最少。

假设盒子摆放 kk 层,从上到下,每一层如果摆满,那么个数分别是 1,1+2,1+2+3,,1+2++k1, 1+2, 1+2+3, \cdots, 1+2+\cdots+k

如果此时盒子还有剩余,那么可以从最低一层继续摆放,假设摆放 ii 个,那么累计可摆放的盒子个数为 1+2++i1+2+\cdots+i

时间复杂度 O(n)O(\sqrt{n}),其中 nn 为题目给定的盒子数量。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def minimumBoxes(self, n: int) -> int:
        s, k = 0, 1
        while s + k * (k + 1) // 2 <= n:
            s += k * (k + 1) // 2
            k += 1
        k -= 1
        ans = k * (k + 1) // 2
        k = 1
        while s < n:
            ans += 1
            s += k
            k += 1
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Able to identify the correct application of binary search over the solution space.

  • question_mark

    Can describe the use of greedy algorithms to optimize floor placement.

  • question_mark

    Comfortable with applying mathematical reasoning to break down the box placement in a cubic space.

warning

常见陷阱

外企场景
  • error

    Overlooking the binary search's application to the answer space, leading to inefficiency.

  • error

    Failing to properly apply greedy placement to maximize the use of space.

  • error

    Not considering mathematical relationships that govern how boxes can fit in the room.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider modifying the constraints by increasing n to test scalability.

  • arrow_right_alt

    Explore different ways of calculating box placement, considering different room dimensions.

  • arrow_right_alt

    Alter the number of boxes to be placed in the room to create varied test cases.

help

常见问题

外企场景

放置盒子题解:二分·搜索·答案·空间 | LeetCode #1739 困难