2.
- sort x坐标(两个端点)
- greedy 按终点的位置来计算不重叠
- 从左往右看,如果是左边点就留下。
- 如果是右边点移除这条线,如果这条线和上一条线不重叠,就算上,不然走下一个点
我用了一个pq来做sort以及从左往右扫的功能
用set来存当前位置的所有存在线段
(sweep line 思想,但是比sweep line简单,不用知道是否重叠)
http://www.geeksforgeeks.org/given-a-set-of-line-segments-find-if-any-two-segments-intersect/
public class LongestLineSetWithoutOverlap {
static class Line{
int left;
int right;
public Line(int left, int right){
this.left= left;
this.right = right;
}
public String toString(){
return this.left+", "+this.right;
}
}
static class Point{
boolean isLeft;
int x;
Line line;
public Point(int x, boolean isLeft,Line line){
this.x = x;
this.isLeft = isLeft;
this.line = line;
}
}
public static int longestNoOverlap(int[][] nums){
PriorityQueue<Point> pq = new PriorityQueue<>((a,b)->(Integer.compare(a.x, b.x)));
int max = 0;
for(int[] line: nums){
Line l = new Line(line[0],line[1]);
Point p1 = new Point(line[0],true,l);
Point p2 = new Point(line[1],false,l);
pq.offer(p1);
pq.offer(p2);
}
Set<Line> T = new HashSet<>();
int pre = Integer.MIN_VALUE;
while(!pq.isEmpty()){
Point p = pq.poll();
if(p.isLeft){
T.add(p.line);
}else{
//remove line
T.remove(p.line);
if(p.line.left >= pre){
max++;
System.out.println(p.line+" "+pre);
pre = p.x;
}
}
}
return max;
}
没有评论:
发表评论