1

我试图找出数组广告中的大多数元素,当我检查小于大小的元素时,此代码工作正常。但是只要任何元素等于数组的大小,它就会给我 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");

    }
}
4

3 回答 3

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 < 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);
  }
}
于 2013-07-13T12:59:08.137 回答
0

问题出在你的:

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]对于一个测试数据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");

    }

}
于 2013-07-13T13:11:53.570 回答
0

使用 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

}
于 2019-05-13T14:56:22.863 回答