LeetCode 715. Range 模块

715. Range 模块

 

【有序集合】用TreeMap来进行有序集合的合并和拆分

class RangeModule {

    // 区间拆分与合并 9:34 10:31

    TreeMap<Integer, Integer> map = new TreeMap();

    public RangeModule() {

    }
    
    public void addRange(int left, int right) {
        Integer start = map.floorKey(right);
        while(start != null){
            int end = map.get(start);
            if(end >= left){
                left = Math.min(left, start);
                right = Math.max(right, end);
                map.remove(start);
            }else{
                break;
            }
            start = map.floorKey(right);
        }
        map.put(left, right);
    }
    
    public boolean queryRange(int left, int right) {
        // for(var k: map.keySet()){
        //     System.out.print("[" + k + "," + map.get(k) + "],");
        // }
        // System.out.println();
        // Integer start = map.floorKey(right);
        // if(start == null) return false;
        // if(start > left) return false;
        // if(map.get(start) < right) return false;
        // return true;
        Integer start = map.floorKey(left);
        if(start == null) return false;
        if(map.get(start) >= right) return true;
        return false;
    }
    
    public void removeRange(int left, int right) {
        //.  3种情况
        //   start________end
        //       left_________right.  [start, left], [end, right]X
        //   start________end
        //. left______________right.   [left, start]X, [end, right]X 
        //.  start______________end
        //      left_______right       [start, left], [right, end]
        
        Integer start = map.floorKey(right);
        while(start != null){
            int end = map.get(start);
            if(start == right) break;
            if(end <= left) break;
            else{
                map.remove(start);
                int s1 = Math.min(start, left);
                int e1 = Math.max(start, left);
                if(s1 == start && e1 == left && s1 != e1) map.put(s1, e1);
                int s2 = Math.min(right, end);
                int e2 = Math.max(right, end);
                if(s2 == right && e2 == end && s2 != e2) {
                    map.put(s2, e2);
                    right --;
                }
            }
            start = map.floorKey(right);
        }
    }
}

/**
 * Your RangeModule object will be instantiated and called as such:
 * RangeModule obj = new RangeModule();
 * obj.addRange(left,right);
 * boolean param_2 = obj.queryRange(left,right);
 * obj.removeRange(left,right);
 */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值