给定一个整数数组,其中元素的取值范围为0到10000,求其中出现次数最多的数

我的菜菜解法:

//给定一个整数数组,其中元素的取值范围为0到10000,求其中出现次数最多的数

 

public class Count{

 public static void main(String args[]){
  int array[] = {1,23,1,222,3,1,2,2,22,355,121,23,23,23,23,23,22,22,22,3,4};
  long start = System.nanoTime();
  int arr[] = new int[array.length];
  /*数组默认值为零
  for(int i = 0; i<arr.length;i++){
   arr[i] = 0;
  }*/
  for(int i = 0; i<array.length;i++){
   for(int j = i+1;j<array.length; j++){
    if(array[i] == array[j]){
     arr[j]++;
    }
   }
  }
  System.out.println("计数数组:");
  for(int i = 0;i<arr.length;i++){
   System.out.print(arr[i] + " ," );
  }
  int max = arr[0];
  int index = 0;
  for(int i =1; i<arr.length; i++){
   if(arr[i]>=max){
    max = arr[i];
    index = i;
   }
  }
  System.out.println();
  System.out.println("出现最多的数:" + array[index]);
  long end = System.nanoTime();
  System.out.println("耗时:" + (end-start) +"ns");
 } 
}

 

牛逼解法:

 


public class Count2 {
 public static void main(String[] args) {
  int[] count = new int[10001];
        int array[] = {1,23,1,222,3,1,2,2,22,355,121,23,23,23,23,23,22,22,22,3,4};

        long start = System.nanoTime();
   /*     for(int num : array){
            count[num]++;
        }
        */
         for(int num=0;num<array.length;num++){
          count[array[num]]++;
         }
         
        int max = -1;
        int loc = -1;
        for (int i = 0;i<count.length;i++) {
            if (max < count[i]) {
                loc = i;
                System.out.println(i);
                max = count[i];
            }
        }
        System.out.println(loc);
        long end = System.nanoTime();
        System.out.println(end-start);
        for(int n:count){
         System.out.print("."+count[n]);
        }
 }
}

posted on 2010-06-01 23:23  Miracle刘  阅读(408)  评论(0编辑  收藏  举报