[英]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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.