Java TreeMap solution


  • 0
    D

    '''
    class RangeModule {
    TreeMap<Integer, Integer> tree;

    public RangeModule() {
        tree = new TreeMap<>();
    }
    
    public void addRange(int left, int right) {
        Map.Entry<Integer, Integer> entry = tree.lowerEntry(left);
        if (entry != null && entry.getValue() >= left) {
            tree.remove(entry.getKey());
            left = entry.getKey();
            right = Math.max(right, entry.getValue());
        }
        while (true) {
            entry = tree.higherEntry(left);
            if (entry == null || entry.getKey() > right) {
                break;
            }
            tree.remove(entry.getKey());
            right = Math.max(right, entry.getValue());
        }
    
        tree.put(left, right);
    }
    
    public boolean queryRange(int left, int right) {
        Map.Entry<Integer, Integer> lowerEntry = tree.floorEntry(left);
        return lowerEntry != null && lowerEntry.getValue() >= right;
    }
    
    public void removeRange(int left, int right) {
        Map.Entry<Integer, Integer> entry = tree.lowerEntry(left);
        if (entry != null && entry.getValue() > left) {
            tree.put(entry.getKey(), left);
            if (entry.getValue() > right) {
                tree.put(right, entry.getValue());
            }
        }
        while (true) {
            entry = tree.ceilingEntry(left);
            if (entry == null || entry.getKey() >= right) {
                break;
            }
            tree.remove(entry.getKey());
            if (entry.getValue() > right) {
                tree.put(right, entry.getValue());
            }
        }
    }
    

    }
    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.