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.

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.


翻译:

假设你是一个很棒的父母并且想要给你的孩子们一些饼干。但是,你应该给每个孩子至多一个饼干。每个孩子 i 都一个贪婪因子 gi,即最小化饼干的规模是的这个孩子感到满足;每个饼干 j 都有规模 sj。如果 sj >= gi,我们将饼干 j 分配给孩子 i,并且孩子 i  将被满足。你的目标是最大化被满足的孩子的数量并且输出最大化的数字。

注意:

你可以假设贪婪因子总是正数的。

你不可以给一个孩子分配超过一个饼干。

例子1:

输入: [1,2,3], [1,1]

输出: 1

解释: 你有 3 个孩子和 2 个饼干,3 个孩子的贪婪因子是 1,2,3。
即便你有 2块饼干,因为它们的规模都是 1,你只能使一个贪婪因子为 1 的孩子满足,你需要输出 1。

例子2:

输入: [1,2], [1,2,3]

输出: 2

解释: 你有 2 个孩子和 3 块饼干。 2 个孩子的贪婪因子为 1,2。
You have 3 cookies and their sizes are big enough to gratify all of the children, 
You need to output 2.


思路:

把题目简化一下,其目的就是要比较数组 s 比数组 g 大的元素的数量。首先将 s 和 g 进行排序,然后依次比较 g 中元素和 s 中元素,若当前的 s[i] 大于 g[j] ,则指针i++,j++,最后结果result++;若 s[i] 小于 g[j], 那么指针 i++,直到俩个数组中的一个扫描到最后则停止,返回result。


C++代码(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

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

int main()
{
	Solution s;
	vector<int> g = { 1,2,3 };
	vector<int> str = { 1,1 };
	int result;
	result = s.findContentChildren(g, str);
	cout << result;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/tel_annie/article/details/80416458