编程语言
首页 > 编程语言> > LeetCode刷题之贪心算法—重叠区间

LeetCode刷题之贪心算法—重叠区间

作者:互联网

Leetcode之 重叠区间 (最少数量箭引爆气球)

1.重叠区间:一组二维数组,它的0列是开始,1列是结束。最少要删除多少个子数组,各子区间才不重叠

 方法一:直接记录交叉区间个数
 static bool cmp(vector<int>& a, vector<int>& b)
    {
        return a[1]<b[1];//右列排序
    }
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
        if(intervals.size()==0) return 0;
        sort(intervals.begin(),intervals.end(),cmp);
        int res=0;//交叉数
        for(int i=1; i<intervals.size();i++)
        {
            if(intervals[i][0]<intervals[i-1][1])
            {
                res++;
                intervals[i][1]=intervals[i-1][1];
            }
        }
        return res++;
 方法二:先找出交叉区间
 static bool cmp(vector<int>& a, vector<int>& b)
    {
        return a[1]<b[1];
    }
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
        if(intervals.size()==0) return 0;
        sort(intervals.begin(),intervals.end(),cmp);
        int res=1;//未交叉数
  int start intervals[0][1];
  for(vector<int>interval:intervals)
  {
  if(start<=interval[0])
  {
  res++;
  start=piont[1];
  }
  }
  return intervals.size() - res;
         

2.引爆气球 :寻找交叉区间,不过边界点重叠也算!!

 ​
 static bool cmp(vector<int>& a, vector<int>& b)
    {
        return a[1]<b[1];
    }
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
        if(intervals.size()==0) return 0;
        sort(intervals.begin(),intervals.end(),cmp);
        int res=1;//未交叉数
  int start intervals[0][1];
  for(vector<int>interval:intervals)
  {
  if(start<interval[0]) //边界重合也算交叉!!
  {
  res++;
  start=interval[1];
  }
  }
  return res; //注意返回值
         

 

TRANSLATE with x English
Arabic Hebrew Polish
Bulgarian Hindi Portuguese
Catalan Hmong Daw Romanian
Chinese Simplified Hungarian Russian
Chinese Traditional Indonesian Slovak
Czech Italian Slovenian
Danish Japanese Spanish
Dutch Klingon Swedish
English Korean Thai
Estonian Latvian Turkish
Finnish Lithuanian Ukrainian
French Malay Urdu
German Maltese Vietnamese
Greek Norwegian Welsh
Haitian Creole Persian  
  TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back

标签:vector,return,int,res,cmp,intervals,刷题,LeetCode,贪心
来源: https://www.cnblogs.com/haipengwu/p/16103034.html