Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Comparator;
- import java.util.List;
- class Covered {
- public static void main(String[] args) {
- final int[][] input = new int[][] {
- {1, 5}, {2, 8}, {9, 10}, {10, 15}, {3, 6}, {18, 20}
- };
- for (int[] s : solve(input)) {
- System.out.println(Arrays.toString(s));
- }
- // Output:
- // [1, 8]
- // [9, 10]
- // [10, 15]
- // [18, 20]
- }
- public static int[][] solve(int[][] segments) {
- final List<Segment> list = new ArrayList<>(segments.length);
- for (int[] segment : segments) {
- list.add(new Segment(segment[0], segment[1]));
- }
- final List<Segment> solution = solve(list);
- final int[][] res = new int[solution.size()][2];
- for (int i = 0; i < solution.size(); i++) {
- res[i][0] = solution.get(i).start;
- res[i][1] = solution.get(i).end;
- }
- return res;
- }
- public static List<Segment> solve(List<Segment> segments) {
- final List<Point> points = new ArrayList<>(segments.size() * 2);
- for (Segment s : segments) {
- points.add(new Point(Type.START, s.start));
- points.add(new Point(Type.END, s.end));
- }
- points.sort(Comparator.comparingInt(o -> o.pos));
- List<Segment> res = new ArrayList<>();
- int start = 0;
- int count = 0;
- for (Point p : points) {
- if (count == 0) {
- assert p.type == Type.START;
- start = p.pos;
- }
- if (p.type == Type.START) count++;
- if (p.type == Type.END) count--;
- if (count == 0) {
- assert p.type == Type.END;
- res.add(new Segment(start, p.pos));
- }
- }
- return res;
- }
- private static class Segment {
- public final int start;
- public final int end;
- private Segment(int start, int end) {
- this.start = start;
- this.end = end;
- }
- }
- private static class Point {
- public final Type type;
- public final int pos;
- private Point(Type type, int pos) {
- this.type = type;
- this.pos = pos;
- }
- }
- private enum Type { START, END }
- }
Add Comment
Please, Sign In to add comment