信封嵌套问题

{[1 ,8][6 ,4][6 ,7][5 ,2][6 ,5][5 ,4][2 ,3][1 ,8]}

上面数组为多个信封宽和高,求最多了嵌套多少个信封(两个信封的高或者宽相同时不能嵌套)?

正确答案为:[2 ,3][5 ,4][6 ,7]

解法:根据宽度进行生序排列,如果宽度相同,则按照高度降序排列(这么做的好处是如果获得宽度相同的第一个信封,只比较自己就可以了,因为后面宽度相同的信封高度一定小于第一个信封,可以减少比较次数);

排序结果:

[1 ,8]
[2 ,3]
[5 ,4]
[5 ,2]
[6 ,7]
[6 ,5]
[6 ,4]

 

    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, 8), new NodeA(6, 4), new NodeA(6, 7), new NodeA(5, 2), new NodeA(6, 5), new NodeA(5, 4), new NodeA(2, 3)};
        //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(5, 3), new NodeA(8, 5), new NodeA(3, 4)};
        //NodeA[] a = {new NodeA(5, 4), new NodeA(6, 4), new NodeA(6, 7), new NodeA(2, 3)};
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i].toString());
        }
        for (int i = 0; i < a.length; i++) {
            for (int j = i; j < a.length; j++) {
                if (a[i].start == a[j].start && a[i].end < a[j].end) {
                    NodeA temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
                if (a[i].start > a[j].start) {
                    NodeA temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i].toString());
        }
        int count = 0;
        for (int i = 0; i < a.length; i++) {
            int temp = 1;
            int end = a[i].end;
            System.out.print(a[i].toString());
            for (int j = i + 1; j < a.length; j++) {
                if (end < a[j].end) {
                    end = a[j].end;
                    temp++;
                    System.out.print(a[j].toString());
                }
            }
            count = count > temp ? count : temp;
            System.out.println();
        }

        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=2247484494&amp;idx=1&amp;sn=0e90d7fbf812fd1f4c408b5cc5fdf8c6&source=41#wechat_redirect

posted @ 2020-07-24 16:15  使用D  阅读(316)  评论(0编辑  收藏  举报