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;
}

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