[LeetCode] Assign Cookies 分點心

 

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.html

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

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.

 

這道題給了咱們一堆cookie,每一個cookie的大小不一樣,還有一堆小朋友,每一個小朋友的胃口也不一樣的,問咱們當前的cookie最多能知足幾個小朋友。這是典型的利用貪婪算法的題目,咱們能夠首先對兩個數組進行排序,讓小的在前面。而後咱們先拿最小的cookie給胃口最小的小朋友,看可否知足,能的話,咱們結果res自加1,而後再拿下一個cookie去知足下一位小朋友;若是當前cookie不能知足當前小朋友,那麼咱們就用下一塊稍大一點的cookie去嘗試知足當前的小朋友。當cookie發完了或者小朋友沒有了咱們中止遍歷,參見代碼以下:cookie

 

解法一:post

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
         int res = 0, p = 0;
         sort(g.begin(), g.end());
         sort(s.begin(), s.end());
         for (int i = 0; i < s.size(); ++i) {
             if (s[i] >= g[p]) {
                 ++res;
                 ++p;
                 if (p >= g.size()) break;
             }
         }
         return res;
    }
};

 

咱們能夠對上述代碼進行精簡,咱們用變量j既能夠表示小朋友數組的座標,同時又能夠表示已知足的小朋友的個數,由於只有知足了當前的小朋友,纔會去知足下一個胃口較大的小朋友,參見代碼以下:url

 

解法二:spa

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        int j = 0;
        sort(g.begin(), g.end());
        sort(s.begin(), s.end());
        for (int i = 0; i < s.size() && j < g.size(); ++i) {
            if (s[i] >= g[j]) ++j;
        }
        return j;
    }
};

 

參考資料:code

https://discuss.leetcode.com/topic/67676/simple-greedy-java-solutionhtm

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索