规律

    1. 贪心算法的规律是通过归纳找出局部的最优解,那么扩展下去找到的一定也是最优解

    学习资料

    1. https://www.ixigua.com/pseries/6803573365928886787_6803240858175930891/

    1、找零问题
    贪心算法找零问题,有面额为100, 50, 20, 10, 5, 1元的钞票,给定任意面额,要求使用最少张数的钞票,求钞票的张数

    1. /**
    2. * 贪心算法找零问题,有面额为100, 50, 20, 10, 5, 1元的钞票,给定任意面额,要求使用最少张数的钞票,求钞票的张数
    3. * @param arr
    4. * @param money
    5. * @return
    6. */
    7. public static int greedy(int[] arr, int money){
    8. int temp= money;
    9. int count = 0;
    10. for (int i = 0; i < arr.length; i++) {
    11. if(temp>arr[i]){
    12. int x = temp / arr[i];
    13. System.out.println("需要取出面额为"+arr[i]+"的钞票"+x+"张");
    14. temp =temp % arr[i];
    15. count+=x;
    16. }
    17. }
    18. return count;
    19. }

    2、饼干分发

    1. /**
    2. * 455. 分发饼干
    3. * https://leetcode-cn.com/problems/assign-cookies/
    4. * 假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i
    5. * ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;
    6. * 并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,
    7. * 这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
    8. *
    9. * 注意:
    10. *
    11. * 你可以假设胃口值为正。
    12. * 一个小朋友最多只能拥有一块饼干。
    13. *
    14. * 来源:力扣(LeetCode)
    15. * 链接:https://leetcode-cn.com/problems/assign-cookies
    16. * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
    17. * @param g
    18. * @param s
    19. * @return
    20. */
    21. public static int findContentChildren(int[] g, int[] s) {
    22. /*
    23. 思路
    24. 1、先将孩子的胃口和饼干的尺寸进行一个排序,从小到大
    25. 2、如果小尺寸的饼干能满足一个孩子,那就没有必要用更大尺寸的饼干,大尺寸的留给大胃口的孩子(贪心)
    26. 3、假设孩子胃口数组g[2,5,9,9,10,15] 饼干尺寸s[1,3,6,8,20]
    27. 4、建立两个指针,一个指向孩子,一个指向饼干
    28. */
    29. Arrays.sort(g);
    30. Arrays.sort(s);
    31. int child = 0;
    32. int cookie = 0;
    33. int count =0;
    34. while (cookie<s.length && child<g.length){
    35. if(s[cookie]<g[child]){
    36. //当前饼干不能满足,也就不能其他孩子,饼干指针后移
    37. cookie++;
    38. }else if(s[cookie]>g[child]){
    39. //当前饼干正好可以满足,分配饼干,并且孩子、饼干指针右移
    40. System.out.println(s[cookie]+"分给孩子"+g[child]);
    41. cookie++;
    42. child++;
    43. count++;
    44. }
    45. }
    46. return count;
    47. }