在java中查找数组中的多数元素

时间:2013-07-13 12:26:00

标签: java

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

    }
}

3 个答案:

答案 0 :(得分:0)

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

这是您稍微修改过的代码。特别是,我摆脱了maj_index变量,因此索引与值混合不会发生。我还使用for-each循环for (int current : a)而不是for循环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);
  }
}

答案 1 :(得分: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]对于测试数据int a[]={2,1,8,8,8,8,6};,元素8是主要的但是[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");

    }

}

答案 2 :(得分: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

}