算法与数据结构

简单贪心算法套路

2018-11-30  本文已影响0人  皆若无殇

这样的问题先设定两个索引表示两个数组的开头和结尾,然后在O(n)时间复杂度下遍历,注意while里的条件设定,否则会发生数组越界错误

  1. 分糖果问题
//g表示贪心指数,s表示饼干大小
    public static int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int sum = 0, gi = g.length-1, si = s.length-1;
        while(si>=0 && gi>=0) {
            if(s[si]>=g[gi]) {
                sum++;
                gi--;
                si--;
            }
            else
                gi--;
        }
        return sum;
    }
  1. leetcode判断子序列
public static boolean isSubsequence(String s, String t) {
       int i = 0, j=0, count = 0;
       while(i<s.length()&&j<t.length()) {
           if(s.charAt(i)==t.charAt(j)) {
               count++;
               i++;
               j++;
           }
           else
               j++;
       }
       return count==s.length();
    }
上一篇 下一篇

猜你喜欢

热点阅读