Leetcode 492. 构造矩形

1.题目描述

作为一位web开发者, 懂得怎样去规划一个页面的尺寸是很重要的。 现给定一个具体的矩形页面面积,你的任务是设计一个长度为 L 和宽度为 W 且满足以下要求的矩形的页面。要求:

1. 你设计的矩形页面必须等于给定的目标面积。

2. 宽度 W 不应大于长度 L,换言之,要求 L >= W 。

3. 长度 L 和宽度 W 之间的差距应当尽可能小。

你需要按顺序输出你设计的页面的长度 L 和宽度 W。

示例:

输入: 4
输出: [2, 2]
解释: 目标面积是 4, 所有可能的构造方案有 [1,4], [2,2], [4,1]。
但是根据要求2,[1,4] 不符合要求; 根据要求3,[2,2] 比 [4,1] 更能符合要求. 所以输出长度 L 为 2, 宽度 W 为 2。

说明:

    1. 给定的面积不大于 10,000,000 且为正整数。
    2. 你设计的页面的长度和宽度必须都是正整数。

2.解法一:耗时216ms

关键为循环条件的设定:循环次数area/2

class Solution {
public:
    vector<int> constructRectangle(int area) {
        unsigned int L,W=0;
        unsigned int L_best,W_best=0;
        int min_gap = area;
        for(int W=1; W<=area/2+1 ;++W){
            L = area/W;
            if(L*W==area && L-W<min_gap){
                L_best = L;
                W_best = W;
                min_gap = L-W;
            }      
        }
        res.push_back(L_best);
        res.push_back(W_best);
        return res;
    }
private:
    vector<int> res;
};

 

3.解法二:耗时0ms

  • 优化循环条件的设置,在草稿纸模拟一个数area=40,即可发现:W不会大于sqrt(area),即W小于等于area的平方根。
  • 直接赋值给vector,返回结果
class Solution {
public:
    vector<int> constructRectangle(int area) {
        unsigned int L,W=0;
        unsigned int L_best,W_best=0;
        unsigned int sz = sqrt(area); //减少了循环次数
        int min_gap = area;
        for(int W=1; W<=sz ;++W){ 
            L = area/W;
            if(L*W==area && L-W<min_gap){
                L_best = L;
                W_best = W;
                min_gap = L-W;
            }      
        }
        res={L_best,W_best};//直接赋值
        return res;
    }
private:
    vector<int> res;
};

 

4.Leetcode上的置顶范例

范例1和2的亮点:

  • (1)我自己也发现了最优的组合,W的值最接近sqrt(area),但自己不会用代码表达,这两个范例解决了这个问题。
  • (2)判断是否整除的方式简洁,我的方法复杂了。
//官网置顶范例0ms
class Solution {
public:
    vector<int> constructRectangle(int area) {
        int width = (int)sqrt(area);
        for (int i = width; i > 0; i--)
        {//i从平方根的初值开始递减,直到整除时返回结果
            if (area % i == 0)
                return { area / i,i };//极简的返回结果
        }
    }
};

 

//官网第二范例4ms
class Solution {
public:
    vector<int> constructRectangle(int area) {
        int i=sqrt(area);
        while(i && area%i)
        {    
            i--;         
        }
        vector<int> out={area/i,i};
        return out;
        
    }
};

 

posted @ 2018-12-21 15:33  Timothy_prayer  阅读(202)  评论(0编辑  收藏  举报