简体   繁体   English

查找数组中某个数字的最大出现次数

[英]Find max occurances of anumber in an array

I've an array {2,22,33,20,222}, passing input as 2. I want find max occurrences of a number for 2.我有一个数组 {2,22,33,20,222},将输入作为 2 传递。我想找到一个数字的最大出现次数为 2。

Output: 222 because 222 contains maximum 2's in given array.输出:222 因为 222 在给定数组中最多包含 2。

Can some one help me to write sample java program of above requirement.有人可以帮我编写上述要求的示例java程序吗?

The easiest (I think) way to achieve that, is to convert each number of your data array to a String .实现这一目标的最简单(我认为)方法是将数据数组的每个数字转换为String Then you can count the occurrences of your input number in this String .然后你可以计算你的输入数字在这个String的出现次数。 Finally a comparator to find the one with the most occurrences will do the job:最后,找到出现次数最多的比较器将完成这项工作:

/**
 * Will return the first number of the data array if none of the numbers contain the input number.
 */
public static int findNumberInArrayWithTheMostOccurrences(Integer[] data, int number) {
    //@formatter:off
    Pattern pattern = Pattern.compile(String.valueOf(number));
    Optional<String> result = Arrays.asList(data).stream()
            .map(String::valueOf) //Convert each number to a String
            .max((stringNum1, stringNum2) -> {//Comparing 2 strings
                Matcher m = pattern.matcher(stringNum1);
                int timesOfString1 = 0;
                while (m.find())
                    timesOfString1++;

                m = pattern.matcher(stringNum2);
                int timesOfString2 = 0;
                while (m.find())
                    timesOfString2++;
                return timesOfString1 - timesOfString2;
        });
    //@formatter:on
    return Integer.parseInt(result.get());
}

And a test unit (JUnit):还有一个测试单元(JUnit):

@Test
public void mainTest() {
    Integer[] data1 = { 2, 22, 33, 20, 222 };
    assertEquals(222, findNumberInArrayWithTheMostOccurrences(data1, 2));

    //Check if it returns the first element of the array when all numbers do not contain it
    assertEquals(2, findNumberInArrayWithTheMostOccurrences(data1, 215));

    Integer[] data2 = { 2, 2224, 3351, 20141414, 22214 };
    assertEquals(20141414, findNumberInArrayWithTheMostOccurrences(data2, 14));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM