LeetCode 题解工作台

构造矩形

作为一位web开发者, 懂得怎样去规划一个页面的尺寸是很重要的。 所以,现给定一个具体的矩形页面面积,你的任务是设计一个长度为 L 和宽度为 W 且满足以下要求的矩形的页面。要求: 你设计的矩形页面必须等于给定的目标面积。 宽度 W 不应大于长度 L ,换言之,要求 L >= W 。 长度 L 和宽…

category

1

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·driven

bolt

答案摘要

class Solution: def constructRectangle(self, area: int) -> List[int]:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

作为一位web开发者, 懂得怎样去规划一个页面的尺寸是很重要的。 所以,现给定一个具体的矩形页面面积,你的任务是设计一个长度为 L 和宽度为 W 且满足以下要求的矩形的页面。要求:

  1. 你设计的矩形页面必须等于给定的目标面积。
  2. 宽度 W 不应大于长度 L ,换言之,要求 L >= W
  3. 长度 L 和宽度 W 之间的差距应当尽可能小。

返回一个 数组 [L, W],其中 LW 是你按照顺序设计的网页的长度和宽度
 

示例1:

输入: 4
输出: [2, 2]
解释: 目标面积是 4, 所有可能的构造方案有 [1,4], [2,2], [4,1]。
但是根据要求2,[1,4] 不符合要求; 根据要求3,[2,2] 比 [4,1] 更能符合要求. 所以输出长度 L 为 2, 宽度 W 为 2。

示例 2:

输入: area = 37
输出: [37,1]

示例 3:

输入: area = 122122
输出: [427,286]

 

提示:

  • 1 <= area <= 107
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
class Solution:
    def constructRectangle(self, area: int) -> List[int]:
        w = int(sqrt(area))
        while area % w != 0:
            w -= 1
        return [area // w, w]
speed

复杂度分析

指标
时间complexity is O(sqrt(area)) because we only check factors down from sqrt(area) until one divides evenly. Space complexity is O(1) since only two variables store L and W.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Expecting recognition that width cannot exceed sqrt(area) for optimal L-W difference.

  • question_mark

    Looking for iterative factor search starting at sqrt(area) rather than brute-force factorization.

  • question_mark

    Candidates should justify why L >= W and why minimal difference occurs at the first factor found from sqrt(area).

warning

常见陷阱

外企场景
  • error

    Forgetting to ensure L >= W, which violates problem constraints.

  • error

    Testing all possible pairs instead of leveraging the math-driven approach, leading to slower solutions.

  • error

    Stopping iteration too early without checking proper division, causing incorrect dimensions.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return all possible rectangles sorted by L-W difference instead of just the optimal one.

  • arrow_right_alt

    Handle non-integer areas by rounding to nearest integers while maintaining L >= W.

  • arrow_right_alt

    Optimize for largest width under additional design constraints, altering the search order from sqrt(area).

help

常见问题

外企场景

构造矩形题解:数学·driven | LeetCode #492 简单