Guest User

Untitled

a guest
Sep 23rd, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.Comparator;
  4. import java.util.List;
  5.  
  6. class Covered {
  7. public static void main(String[] args) {
  8. final int[][] input = new int[][] {
  9. {1, 5}, {2, 8}, {9, 10}, {10, 15}, {3, 6}, {18, 20}
  10. };
  11. for (int[] s : solve(input)) {
  12. System.out.println(Arrays.toString(s));
  13. }
  14.  
  15. // Output:
  16. // [1, 8]
  17. // [9, 10]
  18. // [10, 15]
  19. // [18, 20]
  20. }
  21.  
  22. public static int[][] solve(int[][] segments) {
  23. final List<Segment> list = new ArrayList<>(segments.length);
  24. for (int[] segment : segments) {
  25. list.add(new Segment(segment[0], segment[1]));
  26. }
  27. final List<Segment> solution = solve(list);
  28. final int[][] res = new int[solution.size()][2];
  29. for (int i = 0; i < solution.size(); i++) {
  30. res[i][0] = solution.get(i).start;
  31. res[i][1] = solution.get(i).end;
  32. }
  33. return res;
  34. }
  35.  
  36. public static List<Segment> solve(List<Segment> segments) {
  37. final List<Point> points = new ArrayList<>(segments.size() * 2);
  38. for (Segment s : segments) {
  39. points.add(new Point(Type.START, s.start));
  40. points.add(new Point(Type.END, s.end));
  41. }
  42. points.sort(Comparator.comparingInt(o -> o.pos));
  43.  
  44. List<Segment> res = new ArrayList<>();
  45. int start = 0;
  46. int count = 0;
  47. for (Point p : points) {
  48. if (count == 0) {
  49. assert p.type == Type.START;
  50. start = p.pos;
  51. }
  52. if (p.type == Type.START) count++;
  53. if (p.type == Type.END) count--;
  54. if (count == 0) {
  55. assert p.type == Type.END;
  56. res.add(new Segment(start, p.pos));
  57. }
  58. }
  59. return res;
  60. }
  61.  
  62. private static class Segment {
  63. public final int start;
  64. public final int end;
  65.  
  66. private Segment(int start, int end) {
  67. this.start = start;
  68. this.end = end;
  69. }
  70. }
  71.  
  72. private static class Point {
  73. public final Type type;
  74. public final int pos;
  75.  
  76. private Point(Type type, int pos) {
  77. this.type = type;
  78. this.pos = pos;
  79. }
  80. }
  81.  
  82. private enum Type { START, END }
  83. }
Add Comment
Please, Sign In to add comment