找到没有地图的最重复的整数

时间:2014-04-04 00:15:23

标签: java arrays

我目前在文件中有一个整数的arraylist,如下所示。 1,3,4,3,5,6,5,5我已经对整数进行了排序,但正如你所看到的那样,有一些重复的整数。我想知道如何找到最重复的整数然后将其打印出来?

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;



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

     ArrayList<Integer>myInts = new ArrayList<Integer>();

     Scanner myFile = new Scanner(new File("numbers.txt"));
     while (myFile.hasNextInt())
     {
       myInts.add(myFile.nextInt());

     }
     System.out.println(myInts);
     Collections.sort(myInts);
       System.out.println(myInts);
   }
}

1 个答案:

答案 0 :(得分:0)

你走了:

    int max = 0;
    int nextMax = 0;
    int maxItem = 0;
    for(int i = 0; i < myInts.size(); i++) {
        if(i == 0 )
            continue;
        if(myInts.get(i) == myInts.get(i-1)) {
            if(max > nextMax ) {
                nextMax = max;
                maxItem = myInts.get(i);
            }
            else {
                max++;
                nextMax = max;
                maxItem = myInts.get(i);
            }
        } else {
            max = 0;
        }
    }
    System.out.println(maxItem);