(贪心) leetcode 435 Non-overlapping Intervals, 455 design cookies

思路:

 

 

 

class Solution {
public:
    //自定义比较函数,按照后端点排序
    static bool cmp(vector<int>& a, vector<int>& b){
        return a[1] < b[1];
    }
    
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
        int count = 0;
        sort(intervals.begin(), intervals.end(), cmp);
        for(int i=0; i<intervals.size(); ){
            int right = intervals[i][1];  //右端点
            int j = i+1;
            while(j < intervals.size() && intervals[j][0] < right){
                // 后面区间的左端点小于该区间的右端点
                j++;
                count++;
            } 
            i = j;
        }
        return count;
    }
};

 

 

思路:贪心。分别把胃口数组:g 和 饼干尺寸:s,排序;从胃口数组的第一个索引开始,从饼干数组的第一个遍历,看是否能满足它的胃口。

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        //greedy
        //从小到大排序 O(nlogn)
        sort(g.begin(), g.end());
        sort(s.begin(), s.end());
        
        int j = 0, res = 0;
        for(int i : g){ //O(g)+O(s)
            while(j<s.size() && i > s[j])
                    j++;
            if(j<s.size()){
                res++;
                j++;
            }             
        }
        return res;  
    }
};

 

posted @ 2019-07-24 16:03  爱学英语的程序媛  阅读(209)  评论(0编辑  收藏  举报