算法题(JAVA实现)——网易校招2015

30 篇文章 1 订阅

有两个有序的集合,集合的每个元素都是一段范围,求其交集,例如集合{[4,8],[9,13]}和{[6,12]}的交集为{[6,8],[9,12]}


public class Collection {
    /**
    *集合数据结构
    */
    class Set { 
        int low;
        int high;

        public Set() {
        }

        public Set(int low, int high) {
            this.low = low;
            this.high = high;
        }
    }

    public ArrayList<Set> interSection(ArrayList<Set> A, ArrayList<Set> B) {
        ArrayList<Set> C = new ArrayList<Set>();
        for (Set a : A) {
            for (Set b : B) {
                // 将A中每个元素与B中每个元素求交集,如果所得的集合上界大于下界,则添加到输出集合中
                Set c = new Set();
                c.low = (a.low > b.low) ? a.low : b.low;
                c.high = (a.high < b.high) ? a.high : b.high;
                if (c.low < c.high) {
                    C.add(c);
                }
            }
        }
        return C;
    }

    public static void main(String[] args) {
        Collection collection = new Collection();
        Collection.Set t;
        ArrayList<Set> A = new ArrayList<Set>(); // 初始化输入数组A
        t = collection.new Set(4, 8);
        A.add(t);
        t = collection.new Set(9, 13);
        A.add(t);
        ArrayList<Set> B = new ArrayList<Set>(); // 初始化输入数组B
        t = collection.new Set(6, 12);
        B.add(t);
        ArrayList<Set> C = collection.interSection(A, B); // 数组求交
        for (Set s : C) {
            System.out.println("<"+s.low+","+s.high+">");
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值