[LinkedIn] Add Interval

不多说了,题目如下

public interface Intervals {

    /**
     * Adds an interval [from, to] into internal structure.
     */
    void addInterval(int from, int to);


    /**
     * Returns a total length covered by intervals.
     * If several intervals intersect, intersection should be counted only once.
     * Example:
     *
     * addInterval(3, 6)
     * addInterval(8, 9)
     * addInterval(1, 5)
     *
     * getTotalCoveredLength() -> 6
     * i.e. [1,5] and [3,6] intersect and give a total covered interval [1,6]
     * [1,6] and [8,9] don't intersect so total covered length is a sum for both intervals, that is 6.
     *
     *                   _________
     *                                               ___
     *     ____________
     *
     * 0  1    2    3    4    5   6   7    8    9    10
     *
     */
    int getTotalCoveredLength();
}

解答

public class MyIntervals implements Intervals {
    List<Length> l = new LinkedList<Length>();
    @Override
    public void addInterval(int from, int to) {
        l.add(new Length(x,y));
    }

    @Override
    public int getTotalCoveredLength {
        Collections.sort(l);
        int retLength = 0;
        Length lastone = new Length(0,0);
        for(Length len : l) {
            if(len.x > lastLen.y) {//locate apart
                totalLen += len.y - len.x;
                lastLen = len;
            } else if(len.y >lastlen.y) { //overlapping
                totalLen += len.y-lastLen.y;
                lastLen = len;
            }
            //注意这里不需要考虑如果后一个在前一个里面会怎么样,因为lastLen会维持一样,写一次仍然跟前一个做比较
        }
        return totalLen;
    }

}

public class Length implements Comparable<Length> {
    public int x, y;
    public Length(int x, int y) {
        this.x = x;
        this.y = y;
    }
    @Override
    public compareTo(Length o) {
        if(o.x-this.x == 0) {
            return 0;
        }
        if(o.x-this.x > 0) {
            return -1;
        }
        if(o.x-this.x < 0) {
            return 1;
        }
    }
}

转载于:https://www.cnblogs.com/jxlgetter/p/4395113.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值