为BinarySearch的测试用例添加一个参数:+打印出标准输入中不在白名单上的值;-,则打印出标准输入中在白名单上的值。
代码
public class Main {
public static int rank(int[] a, int t, int lo, int hi, int depth){
while (lo <= hi){
int mid = lo + (hi-lo)/2;
if (a[mid] < t){
lo = mid+1;
}else if (a[mid]>t){
hi = mid-1;
}else{
return mid;
}
depth++;
}
return -1;
}
public static void rank(int[] a, String[] keys, char arg){
for (int i = 0; i < keys.length; i ++){
int index = rank(a,Integer.parseInt(keys[i]), 0, a.length-1, 0);
if (index != -1 && arg != '-'){
System.out.print(keys[i]+" ");
}else if (index == -1 && arg=='+'){
System.out.print(keys[i]+" ");
}
}
}
public static void main(String[] args) {
System.out.print("please choose + or -: ");
StdIn.readString();
char arg = StdIn.readChar();
System.out.print("please intput whiteList(space): ");
String[] keys = StdIn.readLine().split(" ");
int[] a = { 1, 2, 3, 4, 6, 7, 8, 9, 12 };
rank(a, keys, arg);
}
}
结果
please choose + or -: -
please intput whiteList(space): 2 3 5
2 3