Leetcode PHP題解--D111 492. Construct the Rectangle
阿新 • • 發佈:2019-07-31
D111 492. Construct the Rectangle
題目連結
題目分析
給定矩形面積,求出寬高之差最小的邊長。
思路
因為是求出面積,因此先用sqrt函式求開方,向下求整。
再遞減,逐個嘗試面積除以邊長之後餘數是否為0,即能否整除。
為什麼從開方後的值開始?因為題目要求寬高之差要儘可能小。
最終程式碼
<?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]; } }