因为我喜欢在这样的周日下午写文集,
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.Test;
public class TopBottom {
public int[] top;
public int[] bottom;
public TopBottom(int size) {
top = new int[size];
Arrays.fill(top, Integer.MIN_VALUE);
bottom = new int[size];
Arrays.fill(bottom, Integer.MAX_VALUE);
}
public void add(int element) {
int n = Arrays.binarySearch(top, element);
if (n < -1) {
System.arraycopy(top, 1, top, 0, -2 - n);
top[-2 - n] = element;
}
int m = Arrays.binarySearch(bottom, element);
if (m < 0 && bottom.length >= -m) {
System.arraycopy(bottom, -1 - m, bottom, 0 - m, bottom.length + m);
bottom[-1 - m] = element;
}
}
public void add(int... elements) {
for (int each: elements) {
add(each);
}
}
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append('[');
for (int each: bottom) {
buf.append(each);
buf.append(", ");
}
for (int each: top) {
buf.append(each);
buf.append(", ");
}
buf.setLength(buf.length() - 2);
buf.append("]");
return buf.toString();
}
public static class Examples {
@Test
public void shouldHoldOnlyTopFiveAndBottomFive() {
TopBottom tp = new TopBottom(5);
tp.add(5, 15, 10, 1, 12, 8, 11, 2, 16, 14, 9, 3, 20, 7);
assertEquals("[1, 2, 3, 5, 7, 12, 14, 15, 16, 20]", tp.toString());
}
}
}
它使用该Arrays#binarySearch
方法(除了查找现有元素外)如果缺少元素,则将插入点返回到排序列表中。插入点被返回,因此分别(-1-index)
检查是否为负,然后返回表单的表达式以获取插入点或前后点。n
m
-1-n