[leetcode]492. Construct the Rectangle

For a web developer, it is very important to know how to design a web
page’s size. So, given a specific rectangular web page’s area, your
job by now is to design a rectangular web page, whose length L and
width W satisfy the following requirements:

  1. The area of the rectangular web page you designed must equal to the given target area.

  2. The width W should not be larger than the length L, which means L >= W.

  3. The difference between length L and width W should be as small as possible.

作为一名菜鸟首先上来的肯定就是暴力解法,但是最后暴力解法会超时,就放在后面再说了。
现在先说简单的解法。
第一步,是将target因式分解,两个数相乘等于target,那么这两个数最大可能是多少。(很容易入坑的是,除以2,但是实际上,也是重复了不少,因为比如9,9//2=4,事实上是重复了2的,所以应该用开方来解决)
那么就找到中间值mid=int(math.sqrt(area))
第二步,从mid开始判断能否被target整除(这样做能够保证3.L和W之差最小)
第三步,若能返回[area//mid,mid](这样保证了2. 即长比宽要大)若不能,mid减一直到mid=1,返回[area,1]

代码如下:

class Solution(object):
    def constructRectangle(self, area):
        """
        :type area: int
        :rtype: List[int]
        """
        w = int(math.sqrt(area))
        while area % w != 0:
            w -= 1
        return area//w, w

下面将记录一下我的菜鸡代码:

class Solution(object):
   def constructRectangle(self, area):
       """
       :type area: int
       :rtype: List[int]
       """
       res = [[area-1,area,1]]
       
       for i in range(2,area+1):
           if not area%i and area//i >= i:
               res.append([area//i-i,area//i,i])##找出所有可能存在的情况
       
       return min(res)[1:] ##返回差距最小的一组

总结,其实就是没用搞清楚从哪里开始导致了我的版本过于复杂。时间、空间成本太大了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值