Chinaunix首页 | 论坛 | 博客
  • 博客访问: 254759
  • 博文数量: 170
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1709
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-06 18:01
文章分类

全部博文(170)

文章存档

2016年(11)

2015年(130)

2014年(29)

分类: Java

2015-08-04 14:47:03


//Merge Intervals Total Accepted: 40697 Total Submissions: 181352 My Submissions Question Solution 
//Given a collection of intervals, merge all overlapping intervals.
//
//For example,
//Given [1,3],[2,6],[8,10],[15,18],
//return [1,6],[8,10],[15,18].
这道题真的是眨眼间的灵感,一开始没想到先拍个序,一直去用一个数去和现在所有存在的遍历,就算遍历完了,还要有多个还是合并,但是直接拍完序就可以直接来对最后个处理了,使用stack就可以了。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Currency;
import java.util.List;
import java.util.Stack;


class Interval {
     int start;
     int end;
     Interval() { start = 0; end = 0; }
     Interval(int s, int e) { start = s; end = e; }
 }
public class MergeIntervals {


public static void main(String[] args) {
// TODO Auto-generated method stub


}


@SuppressWarnings("unchecked")
public List<Interval> merge(List<Interval> intervals) {
  if(intervals==null||intervals.size()<=1)
  return intervals;
  
  Collections.sort(intervals,new Comparator() {
     @Override
     public int compare(Object o1, Object o2) {
       return ((Interval)o1).start-((Interval)o2).start;
     }
   });
  Stack<Interval> stack=new Stack<>();
  stack.add(intervals.get(0));
  for(int i=1;i<intervals.size();i++){
  Interval cur=stack.pop();
  if(intervals.get(i).start>cur.end){
  stack.push(cur);
  stack.push(intervals.get(i));
  }else{
  cur.end=Math.max(cur.end, intervals.get(i).end);
  stack.push(cur);
  }
  }
  List<Interval> result=new ArrayList<>();
  while(!stack.isEmpty()){
  result.add(stack.pop());
  }
  return result;
}
}



阅读(197) | 评论(0) | 转发(0) |
0

上一篇:Length of Last Word

下一篇:Insert Interval

给主人留下些什么吧!~~