在数组中查找重复项并仅打印一次 [英] Finding Duplicates in Array and printing them only Once

查看:169
本文介绍了在数组中查找重复项并仅打印一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历我的数组并找到所有重复多次的数字:

I am trying to loop through my array and find all the numbers that are repeating more than once:

EG:如果有 1 1 2 3 4

应打印说1次重复多次

这是我的代码,到目前为止我尝试了,但它打印所有重复并继续,如果有 4 4 4 4 3 6 5 6 9 ,它将打印所有的4,但我不想要:

Here is my code and so far what I have tried, however it prints all duplicates and keep going, if there is 4 4 4 4 3 6 5 6 9, it will print all the 4's but i dont want that:

class average {

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

    int numOfLines = 0;
    int sum = 0, mean = 0, median = 0, lq = 0, uq = 0;
    int[] buffer;

    File myFile = new File("num.txt");
    Scanner Scan = new Scanner(myFile);

    while(Scan.hasNextLine()) {
        Scan.nextLine();
        numOfLines++;
    }
    Scan.close();
    Scan = new Scanner(myFile);

    System.out.println("Number Of Lines: " + numOfLines);

    buffer = new int[numOfLines];

    for(int i=0; i<numOfLines; i++) {
        buffer[i] = Scan.nextInt();
    }
    Scan.close();
    Scan = new Scanner(myFile);

    for(int i=0; i<buffer.length; i++) {
        sum = sum+i;
        mean = sum/numOfLines;
    }
    System.out.println("Sum: " + sum);
    System.out.println("Mean: " + mean);

    for(int i=0; i<buffer.length; i++) {
        for(int k=i+1; k<buffer.length; k++) {
            if(buffer[k] == buffer[i]) {
                System.out.println(buffer[k]);
            }
        }
    }


推荐答案

只需将您发现重复的数字添加到某些结构中,例如 HashSet HashMap ,这样您就可以找到它稍后你会发现另一个重复。

Just add the number you will find duplicated to some structure like HashSet or HashMap so you can find it later when you will detect another duplication.

Set<Integer> printed = new HashSet<Integer>();

  for(int i=0; i<buffer.length; i++) {
    for(int k=i+1; k<buffer.length; k++) {
      if(buffer[k] == buffer[i]) {
        Integer intObj = new Integer(buffer[k]);
        if (!printed.contains(intObj)) {
          System.out.println(buffer[k]);
          printed.add(intObj);
        }
        break;
       }
    }
  }

更好的O( n)alghorithm:

Set<Integer> printed = new HashSet<Integer>();

  for(int i=0; i<buffer.length; i++) {
    if (!printed.add(new Integer(buffer[i])) {
       System.out.println(buffer[i]);
    }
  }

这篇关于在数组中查找重复项并仅打印一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆