Last active
September 24, 2018 00:48
-
-
Save hkurokawa/8c77e6f81e26483b14cf51f76e7e7567 to your computer and use it in GitHub Desktop.
Extract the covered area for the given segments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, 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( | |
(o1, o2) -> o1.pos != o2.pos ? o1.pos - o2.pos : o1.type.ordinal() - o2.type.ordinal()); | |
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 } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment