intvs=[[1,3],[2,4],[3,6]]
,这些区间最多有两个区间互不相交,即[[1,3],[3,6]]
,你的算法应该返回 2。注意边界相同并不算相交。
正确的思路其实很简单,可以分为以下三步:
-
从区间集合 intvs 中选择一个区间 x,这个 x 是在当前所有区间中结束最早的(end 最小)。
-
把所有与 x 区间相交的区间从区间集合 intvs 中删除。
-
重复步骤 1 和 2,直到 intvs 为空为止。之前选出的那些 x 就是最大不相交子集。
public static void main(String[] args) { testA(); } static class NodeA { private int start; private int end; public NodeA(int start, int end) { this.start = start; this.end = end; } public String toString() { return "[" + start + " ," + end + "]"; } } public static void testA() { //NodeA[] a = {new NodeA(1, 2), new NodeA(2, 4), new NodeA(5, 6), new NodeA(2, 7), new NodeA(6, 9)}; //NodeA[] a = {new NodeA(1, 2), new NodeA(2, 4), new NodeA(5, 6), new NodeA(2, 7), new NodeA(6, 9)}; NodeA[] a = {new NodeA(1, 2), new NodeA(2, 3), new NodeA(3, 4), new NodeA(1, 3)}; //NodeA[] a = {new NodeA(1, 3), new NodeA(2, 4), new NodeA(3, 6)}; for (int i = 0; i < a.length; i++) { //System.out.println(a[i].toString()); } for (int i = 0; i < a.length; i++) { for (int j = i; j < a.length; j++) { if (a[i].end > a[j].end) { NodeA temp = a[i]; a[i] = a[j]; a[j] = temp; } } } int count = 1; NodeA temp = a[0]; int end = temp.end; for (int j = 1; j < a.length; j++) { if (a[j].start >= end) { count++; end = a[j].end; } } System.out.println(count); for (int i = 0; i < a.length; i++) { System.out.println(a[i].toString()); } }
算法参考:https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247484493&idx=1&sn=1615b8a875b770f25875dab54b7f0f6f&source=41#wechat_redirect