贪心算法

主要难点是

确定这道题能否使用贪心算法来解决。

简单贪心算法

最大的饼干,给最贪心的小朋友。

那么对于倒数第二贪心的小朋友,剩下的也是目前最大的饼干。

可以一直下去。

如果最大的饼干,都没法满足最贪心的小朋友,那么对不起,所有的饼干都满足不了。只能放弃他。

只能让最大的去试一下第二大的小朋友

贪心算法一个特点,最,都是找最大值,最小值。

我的代码

//先排序
        //g是孩子 s是饼干
        Arrays.sort(g);
        Arrays.sort(s);

        int child = g.length-1;
        int cookies = s.length-1;

        int count = 0;

        while(cookies>=0&&child>=0){

            //满足
            if(s[cookies]>=g[child]){
                cookies--;
                child--;
                count++;
            }else{

                //不满足,孩子向前移
                child--;

            }



        }


        return count;

注意Java提供的排序使用方法,并且这个是从小到大的排序

太简单以至于不知道哪里用了贪心算法

我的想法是双指针遍历就好了

 ?????

真的就是双指针就好了,真个还是中等题。。题目超级长,怎么这么简单?

 public boolean isSubsequence(String s, String t) {
        
        int indexS = 0;
        int indexT = 0;

        int sLen = s.length();
        int tLen = t.length();

        while(indexS<sLen&&indexT<tLen){

            if(s.charAt(indexS)==t.charAt(indexT)){
                indexS++;
                indexT++;
            }else{
                indexT++;
            }

        }

        if(indexS==sLen)
            return true;
        else
            return false;
        
    }

原文地址:https://www.cnblogs.com/weizhibin1996/p/9245741.html