【多次过】Lintcode 1209: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.

解题思路1:

    一开始想的是初始化宽从1开始遍历,如果面积能除尽宽则表示存在这样一对可行解,但是还需要检验是否满足规则3,所以设立差值,当可行解的差值小于之前的差值则接受此解,直到遍历完毕则最佳L,W找到。

    这种解法的缺点是一般最优解是在中间部分,而这个是从1开始遍历,做了很多无用功。

class Solution {
public:
    /**
     * @param area: web page’s area
     * @return: the length L and the width W of the web page you designed in sequence
     */
    vector<int> constructRectangle(int area) 
    {
        // Write your code here
        //初始化使得差值最大
        vector<int> LandW{INT_MAX,0};
        int cha = LandW[0] - LandW[1];
        
        int L,W;
        for(int W=1;W<=ceil(double(area)/2);W++)//从宽度开始遍历
        {
            if(area%W == 0 && W <= area/W)//如果L是整数且W<=L时
            {
                int L = area/W;

                if(L-W < cha)//如果差值更小则接受此解
                {
                    cha = L - W;
                    LandW[0] = L;
                    LandW[1] = W;
                }
            }
        }
        return LandW;
    }
};

解题思路2:

    参考网上其他代码,最优解在sqrt(area)周围,所以直接在它周围查找即可。

    先令长l和宽w等于sqrt(area), 如果长x宽得到的面积不等于area,稍微调整l和w的大小:如果面积小了,将长+1;如果面积大了,将宽-1。直到最后l * w == area为止。

class Solution {
public:
    /**
     * @param area: web page’s area
     * @return: the length L and the width W of the web page you designed in sequence
     */
    vector<int> constructRectangle(int area) 
    {
        // Write your code here
        vector<int> result;
        
        int L = sqrt(area);
        int W = sqrt(area);
        
        while(L*W != area)
        {
            if(L*W < area)
                L++;
            else
                W--;
        }
        
        result.push_back(L);
        result.push_back(W);
        
        return result;
    }
};


猜你喜欢

转载自blog.csdn.net/majichen95/article/details/80493330