您的位置:首页 > 其它

[leetcode]解决Assign Cookies的一点小心得

2017-11-01 22:56 477 查看
本次选择的题目是

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.

Solution:

一开始想把每一步的步骤都表示出来:

主要采取的策略是:最小的size匹配最小的需求。如果匹配不了,找次小的size匹配最小的需求,以此类推。

#include <iostream>
#include <vector>
using namespace std;

struct Child
{
int index;
int greed;
bool mark;
};

struct Cookie
{
int index;
int size;
bool mark;
};

class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
if(g.size()==0||s.size()==0)
{
return 0;
}
Child child[g.size()];
Cookie cookie[s.size()];
int max_s = 0;
int max_g = 0;
for (int i = 0;i < s.size();i++)
{
if(s[i]>max_s){
max_s = s[i];
}
}
for (int i = 0;i < g.size();i++)
{
if(g[i]>max_g){
max_g = g[i];
}
}
int min_s = max_s;
int min_g = max_g;
int index_s;
int index_g;
int trytime = 0;
int assigned = 0;
for (int i = 0;i < g.size();i++)
{
child[i].index = i + 1;
child[i].greed = g[i];
child[i].mark = false;
}
for (int i = 0;i < s.size();i++)
{
cookie[i].index = i + 1;
cookie[i].size = s[i];
cookie[i].mark = false;
}
while(trytime != s.size())
{
min_s = max_s;
min_g = max_g;
for (int i = 0;i < s.size();i++)
{
if(cookie[i].mark == false && cookie[i].size <= min_s)
{
index_s = i;
min_s = cookie[i].size;
}
}
cookie[index_s].mark = true;
trytime++;
for (int i = 0;i < g.size();i++)
{
if(child[i].mark == false && child[i].greed <= min_g)
{
index_g = i;

9107
min_g = child[i].greed;
}
}
if(min_s >= min_g&&child[index_g].mark != true)
{
child[index_g].mark = true;
assigned++;

}
}
return assigned;
}
};


只计算匹配成功的次数:

class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(),g.end());
sort(s.begin(),s.end());
int i=0, j=0,count = 0;
while(i<g.size() && j<s.size())
{
if(g[i]>s[j]) j++;
else if(g[i++]<=s[j++]) count++;
}
return count;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: