[LeetCode By Go 29]492. Construct the Rectangle

马上写了30道题目了,使用golang写起题目来代码简洁明了,还可以非常方便的写测试用例,加上Goland可以进行调试,有如神助。
但无论如何,写了测试就会依赖测试判断对错,用了debug就会依赖debug来寻找出错的地方,这些其实都是自己大脑偷懒把压力推到了测试和工具上,在日常开发上可以这样提高代码质量和工作效率,但是在笔试面试时基本上不会用编译器调试代码,更别说写测试用例了。
因此,之后如果能直接把题目解出来,就不写测试用例了,我也省(写)时(烦)间(啦)嘛。

题目

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.

解题思路

求面积的平方根,然后将根作为宽度w,如果area能整除w,则l=area/w, 否则w减1,再进行相同的判断
注意
有人觉得根可以作为宽度递减判断,也可以作为长度递增判断。但是考虑到求平方根后有可能得到小数,如果将根转换为int后,l < (area/l), 与实际不符,因此平方根应该作为宽度

代码

constructRectangle.go

package _492_Construct_the_Rectangle

import "math"

func constructRectangle(area int) []int {
    var ret []int
    sqrtArea := math.Sqrt(float64(area))
    var w int
    w = int(sqrtArea)

    for ; w > 0; w-- {
        if area % w == 0 {
            l := area / w
            ret = []int{l, w}
            break
        }
    }

    return ret
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,570评论 0 23
  • 走过那么多条街,闯过那么多个路口,看到过数不清的风景,错过过数不清的人,做过那么多不切实际的梦。 最后才会明白: ...
    青灰摇阅读 1,094评论 0 0
  • 我们常常会羡慕别人所拥有的,总是感觉自己拥有的没有别人多,这其实是一种错觉,即使自己和别人拥有的一样多,也会潜意识...
    轩筱世界阅读 3,398评论 0 0
  • 突然发现有一点细节没画完,补上 找碴,是哪里没画完?
    AliceTrueLife阅读 1,261评论 1 2
  • 一早,朋友圈里就闹腾了,小梅在圈里发了张借款欠条的照片,没做任何处理,真名实姓,大指印倍儿清晰。下面的评论痛批欠钱...
    牛舌酥阅读 1,499评论 0 2

友情链接更多精彩内容