zoukankan      html  css  js  c++  java
  • 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.

     

    要完成的函数:

    vector<int> constructRectangle(int area) 

     

    说明:

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

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

    代码如下:

        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不断地减一的方法,的确能够节省很多做除法的时间,而两者的效果是一样的。

    代码如下:

        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。

  • 相关阅读:
    Element-ui 中设置input中字符长度并提示
    vue.js如何动态的获取locoalStorage中事先存好的值
    vue中的v-if和v-show的区别详解
    vue.js中ref和$refs的使用及示例讲解
    vue实现输入框的模糊查询的示例代码(节流函数的应用场景)
    flex 如何设置换行flex-wrap
    JS排序之localeCompare( )方法的使用说明及相关案例
    JS—如何按日期对象数组进行排序,然后按时间顺序进行降序排序?
    遇到了编译报错:no method declared with objective-c selector error
    在IT界取得成功应该知道的10件事
  • 原文地址:https://www.cnblogs.com/chenjx85/p/8968936.html
Copyright © 2011-2022 走看看