前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-492-Construct the Rectangle

leetcode-492-Construct the Rectangle

作者头像
chenjx85
发布2018-05-22 16:26:31
5200
发布2018-05-22 16:26:31
举报
文章被收录于专栏:chenjx85的技术专栏

题目描述:

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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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.

要完成的函数:

vector<int> constructRectangle(int area) 

说明:

1、这道题目不难,给定一个乘积,要求输出两个因子(大的在前,小的在后),两个因子的差应该越小越好。

2、看到这些限定条件,我们首选就是开方,然后在开方得到的数值附近找到一个乘积能够整除的数。

代码如下:

代码语言:javascript
复制
    vector<int> constructRectangle(int area) 
    {
        int eu=ceil(sqrt(area));
        while(area%eu)
            eu+=1;
        return {eu,area/eu};
    }

上述代码accepted,实测80ms,beats 27.85% of cpp submissions……

这么低的吗?但我看评论区的代码采用的也是跟我一样的方法,为什么他们就能4ms……

3、改进:

细细对比了一下评论区的代码,他们采用的是eu不断地减一,而我用的是eu不断地加一。

因为eu小的话比较容易除?比如2889除以11,跟2889除以3比起来,肯定后者比较好做除法。

所以如果采用eu不断地减一的方法,的确能够节省很多做除法的时间,而两者的效果是一样的。

代码如下:

代码语言:javascript
复制
    vector<int> constructRectangle(int area) 
    {
        int eu=floor(sqrt(area));
        while(area%eu)
            eu-=1;
        return {area/eu,eu};
    }

实测3ms,beats 98.48% of cpp submissions。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-04-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档