【问题标题】:Find majority element in an array in java在java中的数组中查找多数元素
【发布时间】:2013-07-13 12:25:59
【问题描述】:

我正在尝试找出数组广告中的多数元素,当我检查小于大小的元素时,此代码运行良好。但是只要任何元素等于数组的大小,它就会给我 arrayindexoutofbound 异常。请让我知道如何解决这个问题。

public class MajorityElement {
    public static void main(String[] args) {
        int a[]={2,2,7,5,2,2,6};
        printMajority(a, 7);
    }

    //1st condition to check if element is in majority.
    public static int findCandidate(int a[], int size){
        int maj_index=0;
        int count =1;
        int i;
        size=a.length;

        for(i=1;i<a.length;i++ ){
            if(a[maj_index]==a[i])
                count++;
            else
                count--;
            if(count==0)
            {
                maj_index=a[i];                      //current element takes max_inex position.
                count =1;
            }

        }

        return a[maj_index];
    }

    public static boolean isMajority(int a[], int size, int cand){
        int i, count =0;

        for(i=0;i<a.length;i++)
        {
            if(a[i]==cand)
                count++;
        }
        if(count>size/2){
            return true;
        }
        else {
            return false;
        }

    }

    private static void printMajority(int a[],int size){
        size=a.length;
        int cand=findCandidate( a, 7);

        if(isMajority(a,size,cand))
            System.out.printf("%d",cand);
        else
            System.out.println("no such element as majority");

    }
}

【问题讨论】:

  • 您能否通过示例输入和输出解释您想要实现的目标?我不知道“多数元素”是什么意思,而且鉴于代码是错误的,通过阅读代码很难猜出它的含义。
  • 也许maj_index=a[i]; 应该是maj_index=i;
  • 不要写if (count&gt;size/2) { return true; } else { return false; }。写return count &gt; size / 2;
  • @JBNizet geeksforgeeks.org/majority-element 这可能是一个学校作业。
  • 对了,“多数元素”是什么意思??

标签: java


【解决方案1】:

问题出在maj_index=a[i]; 行。您获取数组的一个单元格的值并将其分配给maj_index,该值随后用作数组的索引(请参阅a[maj_index] == a[i])。因此,如果该位置的值大于数组的大小,则会发生越界情况。

您的代码稍作修改。特别是,我摆脱了maj_index 变量,这样索引与值的混淆就不会发生。我还使用了 for-each 循环 for (int current : a) 而不是 for-loop for(int i = 0; i &lt; a.length; ++i)。最后我去掉了size参数(不用传,可以通过a.length从数组本身推断出来)

public class MajorityElement {

  // 1st condition to check if element is in majority.
  public static int findCandidate(int a[]) {
    int cand = a[0];
    int count = 1;

    for (int i = 1; i < a.length; i++) {
      if (cand == a[i])
        count++;
      else
        count--;
      if (count == 0) {
        cand = a[i];
        count = 1;
      }
    }
    return cand;
  }

  public static boolean isMajority(int a[], int cand) {
    int count = 0;

    for (int current : a) {
      if (current == cand)
        count++;
    }
    return count > a.length / 2;
  }

  private static void printMajority(int a[]) {
    int cand = findCandidate(a);
    if (isMajority(a, cand))
      System.out.printf("%d", cand);
    else
      System.out.println("no such element as majority");

  }

  public static void main(String[] args) {
    int a[] = { 9, 7, 9, 5, 5, 5, 9, 7, 9, 9, 9, 9, 7 };
    printMajority(a);
  }
}

【讨论】:

    【解决方案2】:

    问题出在你的:

    for(i=1;i<a.length;i++ ){
                if(a[maj_index]==a[i])
                    count++;
                else
                    count--;
                if(count==0)
                {
                    maj_index=a[i];                      //current element takes max_inex position.
                    count =1;
                }
    
            }
    
            return a[maj_index];
    

    在这里,您得到的值类似于:a[maj_index] 用于测试数据 int a[]={2,1,8,8,8,8,6}; 元素 8 是主要的,但导致问题的 a[maj_index] 无效,

    相反,完整的代码可以如下所示:

    public class TestMajor {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            int a[]={2,1,8,8,8,8,6};
            printMajority(a, 7);
        }
    
        //1st condition to check if element is in majority.
        public static int findCandidate(int a[], int size){
        int test = a[0];
            int count =1;
            int i;
            size=a.length;
    
            for(i=1;i<a.length;i++ ){
                if(test ==a[i])
                    count++;
                else
                    count--;
                if(count==0)
                {
                test =a[i];                      //current element takes max_inex position.
                    count =1;
                }
    
            }
    
            return test;
        }
    
        public static boolean isMajority(int a[], int size, int cand){
            int i, count =0;
    
            for(i=0;i<a.length;i++)
            {
                if(a[i]==cand)
                    count++;
            }
            if(count>size/2){
                return true;
            }
            else {
                return false;
            }
    
        }
    
        private static void printMajority(int a[],int size){
            size=a.length;
            int cand=findCandidate( a, 7);
    
            if(isMajority(a,size,cand))
                System.out.printf("%d",cand);
            else
                System.out.println("no such element as majority");
    
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      使用 Java 8 的数组中的多数元素或查找元素在数组中出现的最大次数:

      public class MajorityElement {
          public static void main(String[] args) {
              int[] a = {1,3,4,3,4,3,2,3,3,3,3,3};
              List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());
              Map<Integer, Long> map = list.parallelStream()
                      .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
              System.out.println("Map => " + map);
              //{1=1, 2=1, 3=8, 4=2}
              map.entrySet()
              .stream()
              .max(Comparator.comparing(Entry::getValue))//compare the values and get the maximum value
              .map(Entry::getKey)// get the key appearing maximum number of times
              .ifPresentOrElse(System.out::println,() -> new RuntimeException("no such thing"));
      
              /*
               * OUTPUT : Map => {1=1, 2=1, 3=8, 4=2} 
               * 3
               */
              System.out.println("...............");
      
              // A very simple method
              //method 2
              Integer maxAppearedElement = list.parallelStream().max(Comparator.comparing(Integer::valueOf)).get();
              System.out.println(maxAppearedElement);
          }//main
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多