leetcode-455. 分发饼干

题目

https://leetcode-cn.com/problems/assign-cookies/

解法

直觉思路
先排序,然后根据胃口最小的孩子找能满足的最小的饼干

class Solution {

    /**
     * @param Integer[] $g
     * @param Integer[] $s
     * @return Integer
     */
    function findContentChildren($g, $s) {
        sort($g);
        sort($s);
    
        $ret = 0;
		$sKey = 0;
        foreach ($g as $gItem) {
            while(($sItem = reset($s)) !== false) {
                if ($sItem >= $gItem) {
                    $ret ++;
                    array_shift($s);
                    break;
                } else {
                    array_shift($s);
                }
            }
        }
        
        return $ret;
    }
}

因为 array_shift 会对数组做调整的原因,性能会比较差一点,可以做一点小优化

class Solution {
    
    /**
     * @param Integer[] $g
     * @param Integer[] $s
     * @return Integer
     */
    function findContentChildren($g, $s) {
        sort($g);
        sort($s);
        
        $ret  = 0;
        $sKey = 0;
        foreach ($g as $gItem) {
            for ($j = $sKey; $j < count($s); $j++) {
                $sKey++;
                if ($s[$j] >= $gItem) {
                    $ret++;
                    break;
                }
            }
        }
        
        return $ret;
    }
}
posted @ 2021-11-09 22:49  吴丹阳-V  阅读(23)  评论(0编辑  收藏  举报