我正在尝试解决 interviewstreet 的中值挑战。我在这里看到了一个类似的问题:interviewstreet medium challenge,但我想找出我的方法有什么问题。我正在使用二进制搜索和排序的 ArrayList 来找出每个点的中位数。只有第 1 次、第 3 次和第 10 次测试通过,其余测试均以错误答案失败。问题:http ://pastebin.com/1QhbiB2U 这是代码:
/**
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long N = in.nextLong();
List<Long> list = new ArrayList<Long>();
for(int i=0; i<N; i++){
String op = in.next();
long number = in.nextLong();
performOperation(op, number, list);
}
}
private static void performOperation(String op, long number, List<Long> list) {
int index = Collections.binarySearch(list, number);
if(op.equalsIgnoreCase("r")){
if(index < 0){
System.out.println("Wrong!");//Doesn't exist
return;
}else{
list.remove(index);//Remove any one occurence
}
}else{
if(index < 0){
list.add(-index-1, number);//Add in sorted list
}else{
list.add(index, number);//Add where the same number exists, should still be sorted.
}
}
if(list.size() == 0){
System.out.println("Wrong!");
}else if(list.size()%2 == 0){
double median = (list.get(list.size()/2) + list.get(list.size()/2 - 1))/2.0;
if(median == Math.ceil(median))
System.out.println((long)median);
else
System.out.println(median);
}else{
System.out.println(list.get((list.size()-1)/2));
}
}