实现 interval add,求取覆盖范围

某家店面题目。

public interface Intervals {
    TreeMap map = new TreeMap<>();

    // add a new interval
    void add(int from, int end) {
        map.put(from, true);
        map.put(to, end);
    }

    // get the total coverage covered by intervals
    int getTotalCoveredLength() {
        int totalLen = 0;
        int count = 0;
        int start = 0;

        Iterator iter = map.iterator();
        while(iter.hasNext()) {
            Map.Entry entry = iter.next();
            if (iter.getValue()) {
                count++;
                if (count == 1) {
                    start = iter.getKey();
                }
            } else {
                count--;
            }

            if (count == 0) {
                totalLen += iter.getKey() - start;
            }
        }

        return totalLen;
    }
}

你可能感兴趣的:(实现 interval add,求取覆盖范围)