二分查找找到不重复的元素 java

binary search find the element that does not repeat java

//package alg;
import java.io.*;

//import java.io.File;
//import java.io.FileNotFoundException;
//import java.io.InvalidCommandException;
//import java.io.NumberFormatException;
import java.util.Arrays;
//import java.util.ArrayList;
//import java.util.List;
import java.util.Scanner;

//import javax.sound.sampled.Line;

public class FindOut
{
    public static void Find(int [] Ray, int min , int max)
    {


        if(min > max)
        {
            return;
        }

        if(min == max)
        {
            System.out.println(Ray[min]);
            return;

        }

        int med = (min + max)/2;


        if(med % 2 == 0)
        {

            if(Ray[med] == Ray[med + 1])
                Find(Ray, med + 2, max);

            else
                Find(Ray, min, med);

        }

        else //if(med % 2 == 1)
        //{

            if(Ray[med] == Ray[med-1])

                Find(Ray, med + 1 , max);

            else
                Find(Ray, min, med - 1);
    //  }



    }





    public static void main(String [] args) throws FileNotFoundException
    {

        @SuppressWarnings("resource")


        File file = new File(args [0]);

        Scanner scanner = new Scanner(file);


                try
        {

            int[] Ray = new int [5];    

            while(scanner.hasNext())
            {

                String num = scanner.next();



                 Ray = Arrays.stream(num.split(",")).mapToInt(Integer::parseInt).toArray();


                Find(Ray,0, Ray.length-1);





            }


                //  File inputFile = new File(num);


        }
        catch(NumberFormatException ex)
        {

        }

 }
}

我需要的是通过命令行输入一个文件,它会读取里面的整数并将它们放入一个数组中,我通过函数发送该数组以找到只出现一次的元素,例如

3 , 3 ,48, 48, 65, 95, 95

应该输出

65

但它的作用是

3 3 48 48 65 95 95

我知道这不是我用硬代码测试过的功能,运行 从逻辑上一步一步地通过主要逻辑所以任何人都可以解释这个问题吗?

读取文件的方式有问题。似乎代码期望一行包含整个数字列表。但是,Scanner 使用空格作为默认分隔符。 Find 最终为文件中的每个数字调用一次。

要修复它,可以像这样指定分隔符:

Scanner scanner = new Scanner(file).useDelimiter(",");

这意味着不需要您正在做的 mapToInt 事情。相反,我建议您使用 Collections 中的容器,例如 ArrayList,并在转换为整数后将数字附加到其中。

public static void main(String[] args) throws FileNotFoundException {
    @SuppressWarnings("resource")
    File file = new File(args [0]);
    Scanner scanner = new Scanner(file).useDelimiter(",");

    try {
        ArrayList<Integer> Ray = new ArrayList<>();

        while (scanner.hasNext()) {
            String num = scanner.next().trim();
            Ray.add(Integer.parseInt(num));
        }

        scanner.close();
        int[] arr = Ray.stream().mapToInt(i -> i).toArray();
        Find(arr, 0, arr.length - 1);
    } catch (NumberFormatException ex) {

    }
}

使用 ArrayList 可以根据需要进行扩展,这与具有固定大小的数组不同。这很方便,因为这意味着您不必提前知道文件中的整数数量。

为了与您的 Find 函数保持兼容性,我将 ArrayList 转换回普通数组。但是,我建议您更新函数以接受 ArrayList.