中三A105论坛
请选择 进入手机版 | 继续访问电脑版

注册 登录
查看: 836|回复: 0

Java 取时间段并集(https://ideone.com/fRb8tM)

[复制链接]

105

主题

119

帖子

553

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
553
发表于 2019-4-22 13:09:22 | 显示全部楼层 |阅读模式
  • * package whatever; // don't place package name! */

  • import java.util.*;
  • import java.lang.*;
  • import java.io.*;

  • /* Name of the class has to be "Main" only if the class is public. */
  • class Ideone
  • {
  •   public static void main (String[ args) throws java.lang.Exception
  •   {
  •     List<MyTime> myTimeList = new ArrayList<MyTime>();
  •     myTimeList.add(new MyTime(7, 9));
  •     myTimeList.add(new MyTime(9, 15));
  •     myTimeList.add(new MyTime(2, 6));
  •     myTimeList.add(new MyTime(1, 5));
  •     myTimeList.add(new MyTime(2, 4));
  •     myTimeList.add(new MyTime(10, 12));

  •     Collections.sort(myTimeList);

  •     System.out.println(myTimeList.size());

  •     Stack s = new Stack();
  •     Stack e = new Stack();
  •     s.push(0);
  •     e.push(0);
  •     for (MyTime time : myTimeList)
  •     {
  •       System.out.println(time.getStart() + " " + time.getEnd());
  •       if (time.getStart() > time.getEnd())
  •         throw new Exception("The time is incorrect.");

  •       if (time.getStart() > (int)e.peek()) //没有交集
  •       {
  •         s.push(time.getStart());
  •         e.push(time.getEnd());
  •       }
  •       else if (time.getEnd() > (int)e.peek()) //有部分交集,取并集
  •       {
  •         e.pop();
  •         e.push(time.getEnd());
  •       }
  •       //else {} //完全被覆盖
  •     }

  •     int total = 0;
  •     while (!s.empty())
  •     {
  •       System.out.println(s.peek() + " ~ " + e.peek());
  •       total += (int)e.pop() - (int)s.pop();
  •     }
  •     System.out.println("Total: " + total);
  •   }
  • }

  • class MyTime implements Comparable<MyTime>
  • {
  •   private int start;
  •   private int end;
  •   MyTime(){}
  •   MyTime(int start, int end)
  •   {
  •     this.start = start;
  •     this.end = end;
  •   }
  •   public int getStart()
  •   {
  •     return start;
  •   }
  •   public int getEnd()
  •   {
  •     return end;
  •   }
  •   public int compareTo(MyTime other)
  •   {
  •     if (start == other.start)
  •     {
  •       return other.end - end;
  •     }
  •     return start - other.start;
  •   }
  • }


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回列表 返回顶部