1. 程式人生 > >LeetCode 492. 構造矩形(C、C++、python)

LeetCode 492. 構造矩形(C、C++、python)


作為一位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。

說明:

給定的面積不大於 10,000,000 且為正整數。

你設計的頁面的長度和寬度必須都是正整數。

 

本題主要考察演算法的時間效能,假設n是area的開方,當數字非常大時,從n+1往area開始遍歷,就會超時,因此從n-1往1遍歷。

C

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* constructRectangle(int area, int* returnSize) 
{
    int* res=(int*)malloc(sizeof(int)*2);
    int n=(int)sqrt(area);
    if(n==sqrt(area))
    {
        res[0]=n;
        res[1]=n;
    }
    else
    {
        int i=n;
        while(i)
        {
            if(0==area%i)
            {
                res[1]=i;
                res[0]=area/i;
                break;
            }
            i--;
        }
    }
    *returnSize=2;
    return res;
}

C++

class Solution {
public:
    vector<int> constructRectangle(int area) 
    {
        int n=(int)sqrt(area);
        if(n==sqrt(area))
        {
            return {n,n};
        }
        int L;
        int W;
        for(int i=n;i>0;i--)
        {
            if(0==area%i)
            {
                return {area/i,i};
            }
        }
    }
};

python

class Solution(object):
    def constructRectangle(self, area):
        """
        :type area: int
        :rtype: List[int]
        """
        n = int(area**0.5)
        if n==area**0.5:
            return [n,n]
        for i in range(n,0,-1):
            if 0==area%i:
                return [area//i,i]