某家店面题目。
public interface Intervals {
TreeMap<Integer, Boolean> 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<Integer, Boolean> iter = map.iterator();
while(iter.hasNext()) {
Map.Entry<Integer, Boolean> entry = iter.next();
if (iter.getValue()) {
count++;
if (count == 1) {
start = iter.getKey();
}
} else {
count--;
}
if (count == 0) {
totalLen += iter.getKey() - start;
}
}
return totalLen;
}
}