所以我的程序遇到了问题。我正在尝试修改 BinarySearch 以便获得一对数字。我试图确定排序数组中的何处有数字 x 的多个实例。我需要在屏幕上显示第一个和最后一个索引。我不断添加几个 if 语句,但是当我这样做时,我没有进行任何比较。现在,当我尝试返回 Pair(left, right) 时,我收到错误:在该特定代码行上找不到符号。我目前没有任何东西可以检查左侧或右侧。我只是想让我的代码编译,但现在无法让它工作。任何输入都会有帮助。并不是要求你为我做我的工作,只是在正确的方向上稍微插入一下。
import java.util.*;
import java.io.*;
public class Test_BinarySearchDup{
private static class Pair{
public int left;
public int right;
public Pair(int left, int right){
this.left = left;
this.right = right;
}
}
public static void main(String[] args) throws IOException{
String file = args[0];
int x = Integer.parseInt(args[1]);
Scanner fin = new Scanner(new FileReader(file));
int count = 0;
while(fin.hasNext()){
fin.nextInt();
count++;
}
fin.close();
int[] array = new int[count];
fin = new Scanner(new FileReader(file));
while(fin.hasNext()){
for(int i = 0; i < array.length; i++){
array[i] = fin.nextInt();
}
}
fin.close();
Pair numbers = BinarySearchDup(array, x, 0, (array.length - 1));
System.out.println("[" + numbers.left + "," + numbers.right + "]");
}
public static Pair BinarySearchDup(int[] A, int x, int low, int high){
int mid = (low + high) / 2;
int left = 0, right = 0;
while(low <= high){
mid = (low + high) / 2;
if(A[mid] == x){ //if A[mid] == x we need to check left and right to make sure that there are no other copies of the number
//checking to the left
return BinarySearchDup(A, x, low, mid - 1);
}
else if(A[mid] < x)
return BinarySearchDup(A, x, mid + 1, high);
else
return BinarySearchDup(A, x, low, mid - 1);
}
return new Pair(left, right);
}
}
最佳答案
这将修复您的语法错误:
改变
return Pair(left, right);
到
return new Pair(left, right);
^^^
不过,我还没有检查你的代码的逻辑。
关于java - 编译器错误? Java二分查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15868735/