leetcode.455.Assign Cookies

Description

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

Note:
You may assume the greed factor is always positive.
You cannot assign more than one cookie to one child.

Example 1:

Input: [1,2,3], [1,1]

Output: 1

Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. 
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.

Example 2:

Input: [1,2], [1,2,3]

Output: 2

Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. 
You have 3 cookies and their sizes are big enough to gratify all of the children, 
You need to output 2.

sln

通過簡單分析,可以發現這道題用貪婪算法來實現的話,就是對於每個小孩,儘量找比他的g值大的s值列表中最小的s值。
那麼我們首先對g和s兩個列表進行升序排序,分別從頭開始遍歷g和s兩個數組,對於每個g和s值,如果g大於s,則當前s無法滿足當前g,s指向下一個值。如果g小於等於s,那麼當前s是最適合當前g的值(因爲s和g都已經排過序了),因此s和g都指向下一個值。這樣下來,對於排序後的s和g,我們只需要進行一次遍歷就可以找出結果。遍歷的時間複雜度爲O(n),而排序的複雜度爲O(nlogn)。因此整個算法的複雜度爲O(nlogn)。python實現如下:

class Solution(object):
    def findContentChildren(self, g, s):
        """
        :type g: List[int]
        :type s: List[int]
        :rtype: int
        """
        if len(g) == 0 or len(s) == 0:
            return 0
        g = sorted(g)
        s = sorted(s)
        g_index = 0
        s_index = 0
        count = 0
        while g_index < len(g) and s_index < len(s):
            if g[g_index] <= s[s_index]:
                g_index += 1
                s_index += 1
                count += 1
            else:
                s_index += 1
        return count

提交上述算法後發現僅僅比75%+的提交快,然而快速瀏覽了下discussion卻發現大家都是在說這種O(nlogn)的實現,所以暫時還沒有進一步優化的思路。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章