贪心算法或贪心思想采用贪心的策略,保证每次操作都是局部最优的,从而使最后得到的结果是全局最优的
import java.util.*;
/* 有一群孩子和一堆饼干,每个孩子有一个饥饿度,
每个饼干都有一个大小。每个孩子只能吃一个饼干,
且只有饼干的大小不小于孩子的饥饿度时,这个孩子才能吃饱。
求解最多有多少孩子可以吃饱。*/
public class AssignCookies {
private static HashMap<Integer, Integer> map = new HashMap<>();
public static void main(String[] args) {
int[] childs = {2,8};
int[] cookies = {1,2,7};
System.out.println(assignCookies(childs, cookies));
Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
for (Map.Entry<Integer, Integer> entry : entries) {
Integer child = entry.getKey();
Integer cookie = entry.getValue();
System.out.println(child + "==" + cookie );
}
}
/*/**
* @Description:
* @Param: [childs, cookies]
* @return: java.lang.Integer
* @Date: 2021/4/24
*/
public static Integer assignCookies(int[] childs , int[] cookies){
//贪心算法,先让饥饿度小的吃饱
Arrays.sort(childs);
Arrays.sort(cookies);
int child = 0;
int cookie = 0;
while (child <childs.length && cookie < cookies.length){
if( childs[child] <= cookies[cookie]){
map.put(childs[child],cookies[cookie]);
child++;
}
cookie++;
}
return child;
}
}