【问题标题】:Given an array, return the element that occurs the most number of consecutive times. In Java [closed]给定一个数组,返回连续出现次数最多的元素。在Java中[关闭]
【发布时间】:2021-02-19 05:31:18
【问题描述】:

在 Java 中,给定数组 A[a,a,b,b,b,c,d,e,e] 返回 'b',因为它连续出现的次数比数组中的任何其他元素都多。我尝试将每个元素与下一个元素进行比较,如果它们匹配,则增加一个计数,然后返回计数最高的元素,但我不知道如何将它实现到代码中。

【问题讨论】:

  • 你能分享你试过的代码吗?这个问题是 CS 中的基本问题。
  • 您可以发布您尝试过的蛮力解决方案。我们很乐意提出优化建议。

标签: java arrays algorithm


【解决方案1】:

注意 - 这假设字符在 BMP 中

  1. 保持 4 个状态 - prev charactercurrent charactercurrent countmax count
  2. 初始prev character 为一些无效字符或为空
  3. 将计数初始化为零
  4. 遍历字符,如果在任何时候当前字符和前一个字符不匹配,则重置当前字符和当前计数
  5. 当当前计数大于最大计数时,将当前字符更新为最大字符并更新最大计数
    public static void main(String[] args) {
        char[] input = new char[] {'a', 'b', 'b', 'b', 'b', 'c', 'd', 'e', 'e'};
        if (input.length == 0) {
            return;
        }
        char prev = (char) (input[0] - 1); // choose a character other than first character
        char maxChar = prev;
        int maxCount = 0;
        int currentCount = 0;
        for (final char current : input) {
            if (prev != current) {
                prev = current;
                currentCount = 0;
            }
            currentCount++;
            if (currentCount > maxCount) {
                maxCount = currentCount;
                maxChar = current;
            }
        }
        System.out.println(maxChar);
    }

【讨论】:

    【解决方案2】:

    只需将当前元素与前一个元素进行比较,计算连续元素的数量,如果检测到连续元素,则检查它是否大于现有最大值并跟踪该值:

    public static int findMostConsecutive(int ... arr) {
        int res = arr[0];
        int count = 1;
        int maxCount = 1;
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] == arr[i - 1]) {
                count++;
                if (count > maxCount) {
                    maxCount = count;
                    res = arr[i];
                }
            }
            else {
                count = 1;
            }
        }
        return res;
    }
    

    测试:

    
    System.out.println("Most consecutive: " + findMostConsecutive(1, 2, 1, 1, 3, 3, 3, 4, 2));
    System.out.println("Most consecutive: " + findMostConsecutive(2, 2, 2, 2, 3, 3, 3, 3));
    System.out.println("Most consecutive: " + findMostConsecutive(2, 2, 2, 2, 3, 3, 3, 3, 3, 3));
    

    输出

    Most consecutive: 3
    Most consecutive: 2
    Most consecutive: 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多