Open atomiCat opened 6 years ago
public class Main { static int[][] input = { {1, 0, 0, 1}, {1, 0, 4, 5}, {3, 2, 2, 5}, {2, 1, 5, 6} }; public static void main(String[] a) { Rectangle[] r = new Rectangle[input.length]; for (int i = 0; i < input.length; i++) r[i] = new Rectangle(input[i]); //按照底边从小到大排序 Arrays.sort(r, Comparator.comparingInt(rect -> rect.d)); for (int i = 1; i < r.length; i++) r[i - 1].append(r[i]); Rectangle that = r[0], next = that.next; boolean merged = false;//记录本轮循环有没有矩形被合并 while (that != null) { if (next == null || that.u < next.d) { if (merged) merged = false; else that = that.next; if (that != null) next = that.next; } else { if (!((next.l < that.l && next.r < that.l) || (next.r > that.r && next.l > that.r))) { that.merge(next); next.remove(); merged = true; } next = next.next; } } that = r[0]; do { System.out.print(that + ",\n"); } while ((that = that.next) != null); } } class Rectangle { int u, d, l, r; Rectangle prev, next; public Rectangle(int[] a) { u = a[0]; d = a[1]; l = a[2]; r = a[3]; } public void merge(Rectangle rect) { u = Math.max(u, rect.u); l = Math.min(l, rect.l); r = Math.max(r, rect.r); } public void append(Rectangle r) { this.next = r; if (r != null) r.prev = this; } public void remove() { this.prev.append(this.next); } @Override public String toString() { return "[" + u + "," + d + "," + l + "," + r + ']'; } }
Question_ID: Q003
Language: JAVA
Time Cost: 120-mins
Time Complexity: 菜鸡算不出来感觉应该是O(n^2)求大佬帮忙分析啊
Solution
My Code
Other