[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.

You need to output the length L and the width W of the web page you designed in sequence.

Example:

Input: 4
Output: [2, 2]
Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. 
But according to requirement 2, [1,4] is illegal; according to requirement 3,  [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.

Note:

  1. The given area won't exceed 10,000,000 and is a positive integer
  2. The web page's width and length you designed must be positive integers.
难度

Easy

方法

将面积area开方后取整获得width,如果width不能被area除尽,则将width递减,直至width能被area除尽,area/width即为length

python代码
import math

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

Solution().constructRectangle(4) == [2,2]
Solution().constructRectangle(10) == [5,2]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,436评论 0 23
  • 本文原创首发于微信公众号:snk147,转载请注明。 为期一周的玉山斯诺克世界公开赛落下帷幕,丁丁摘得桂冠,将职业...
    keisme阅读 3,325评论 0 0
  • 每个喜欢文字人,在他的身体里都有另外一个灵魂…… 朋友说“如果你不懂我的文字,那你就不懂我的故事。”是的,一句值得...
    浊酒清忧阅读 4,987评论 0 3
  • 生活里有2种事,1是喜欢的事,另1是不喜欢的事。喜欢的事总是马上做快快做多多做,不喜欢的则慢慢做以后做少少做。人...
    俞晴天阅读 1,261评论 0 0
  • 缘起 上次和辉哥聊完之后,认认真真思考了一下我转行做培训师的可能性,拖到某一天列了个思维导图,发现如果转行的话需要...
    黄小小茶阅读 2,985评论 0 2