Algorithms—56.Merge Intervals
2015-07-09 15:09
639 查看
思路:原来以为很简单,结果发现会出现同一个点原地开始原地结束的情况。先遍历查询,然后把所有的坐标装入map中,value的值代表对应的属性,然后读取。
耗时:448ms,中游,第一次看到C语言不是第一。。。
/** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class Solution { public List<Interval> merge(List<Interval> intervals) { //0开头,2结束,-1原地,1正常 Map<Integer, Integer> map=new HashMap<Integer, Integer>(); int sum=0; for (int i = 0; i <intervals.size(); i++) { int s=intervals.get(i).start; int e=intervals.get(i).end; if (e>sum) { sum=e; } if (s==e) { if (map.get(s)==null) { map.put(s, -1); } }else { for (int j = s; j <=e; j++) { if (j==s) { if(map.get(j)==null||map.get(j)==-1||map.get(j)==0){ map.put(j, 0); }else { map.put(j, 1); } }else if (j==e) { if (map.get(j)==null||map.get(j)==-1||map.get(j)==2) { map.put(j, 2); }else { map.put(j, 1); } }else { map.put(j, 1); } } } } boolean flag=true; List<Interval> answerList=new ArrayList<Interval>(); int s=0; int e=0; for (int i = 0; i <sum+2; i++) { if (flag) { if (map.get(i)!=null&&map.get(i)==-1) { answerList.add(new Interval(i,i)); }else if (map.get(i)!=null) { s=i; flag=false; } }else { if (map.get(i)==null||map.get(i)==2) { flag=true; e=i; answerList.add(new Interval(s,e)); s=0; } } } return answerList; } }
耗时:448ms,中游,第一次看到C语言不是第一。。。
相关文章推荐
- Dragon of Loowater
- [Algorithm] 字符串匹配算法——KMP算法
- 使用if和goto语句构造循环
- Algorithms—54.Spiral Matrix
- 你所不知道的Google广告阴暗面
- mongo 中 高级查询之 group
- golang
- POJ2762 Going from u to v or from v to u? 强连通+缩点
- 极课 good
- Algorithms—53.Maximum Subarray
- Google Volley 解析参考文章
- 算法基础:正整数指定规则排序问题(Golang实现)
- win7配置go环境
- iphone 开发Categories 、Extensions 区别 --转
- Algorithms—50.Pow(x, n)
- CodeForces 228E The Road to Berland is Paved With Good Intentions (2-Sat)
- Siri变得越来越像Google Now
- VIEWGOOD(远古)建立区域性教育资源公共平台的解决方案
- hdu 4760 - Good Firewall(Trie)
- 科技企业是员工的最佳“父母”?