Leetcode PHP题解--D111 492. Construct the Rectangle

D111 492. Construct the Rectangle

题目连接

492. Construct the Rectanglephp

题目分析

给定矩形面积,求出宽高之差最小的边长。函数

思路

由于是求出面积,所以先用sqrt函数求开方,向下求整。
再递减,逐个尝试面积除以边长以后余数是否为0,即可否整除。.net

为何从开方后的值开始?由于题目要求宽高之差要尽量小。code

最终代码

<?php
class Solution {

    /**
     * @param Integer $area
     * @return Integer[]
     */
    function constructRectangle($area) {
        $mid = floor(sqrt($area));
        for($i=$mid; $i>1; $i--){
            if($area%$i == 0){
                return [$area/$i, $i];
            }
        }
        return [$area, 1];
    }
}

若以为本文章对你有用,欢迎用爱发电资助。leetcode

相关文章
相关标签/搜索