zoukankan      html  css  js  c++  java
  • (贪心) 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;  
        }
    };
  • 相关阅读:
    作业一
    工作日志(二)
    工作日志(三)
    工作日志(四)
    工作日志(一)
    团队项目开发日志(四)
    团队项目开发日志(三)
    团队项目开发日志(二)
    团队项目开发日志(一)
    第四次作业
  • 原文地址:https://www.cnblogs.com/Bella2017/p/11238671.html
Copyright © 2011-2022 走看看