1. 程式人生 > >Leetcode PHP題解--D111 492. Construct the Rectangle

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

D111 492. Construct the Rectangle

題目連結

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];
    }
}

若覺得本文章對你有用,歡迎用