0

所以我的程序遇到了问题。我正在尝试修改 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);
}
}
4

1 回答 1

3

This will fix your syntax error:

Change

return Pair(left, right);

to

return new Pair(left, right);
       ^^^ 

I haven't checked the logic of your code, though.

于 2013-04-07T22:48:40.593 回答