facebook 面经

FB 电面 寻找两个区间表的交集

2018-09-14  本文已影响0人  Anseis

双指针

public List<Interval> commonOnlineInterval(List<Interval> a, List<Interval> b){
        int i = 0, j =0;
        List<Interval> res = new ArrayList<Interval>();
        while(i<a.size()&&j<b.size()){
            if(a.get(i).start >= b.get(j).end)j++;
            else if(b.get(j).start >= a.get(i).end) i++;
            else if(a.get(i).start < b.get(j).end){
            res.add(new Interval(Math.max(a.get(i).start,b.get(j).start),Math.min(a.get(i).end,b.get(j).end)));
            j++;
            }
            else if(b.get(j).start < a.get(i).end){
            res.add(new Interval(Math.max(a.get(i).start,b.get(j).start),Math.min(a.get(i).end,b.get(j).end)));
            i++;
            }
        }
        return res;
    }
上一篇 下一篇

猜你喜欢

热点阅读