您的位置:首页 > 其它

数组中出现次数最多的元素_legend

2014-05-22 13:43 218 查看

数组中出现次数 最多的 元素 :

(方法一) :

/*

先快速排序,复杂度为O(n*lgn),然后从有序数组中找到重复次数最多的元素,

复杂度为O(n);

所以整体复杂度为 O(n*lgn+n);

*/

 quickSort(arr,0,length);

 void mostRepeatedElement(int * arr,int length,int* mostRepeatedEle,

                         int * mostRepeatedCount){

      int tmp_value=arr[0];

      int tmp_count=1;

      /*初始时tmp_count=1,tmp_value=arr[0]

      初始时*mostRepeatedEle=arr[0]

      *mostRepeatedCount=1;

      注意:tmp_value,以及tmp_count记录的是最近访问的

      元素,以及出现次数。

      */

      int  i;

      for( i=1;i<length;i++)

      /*因为初始时,tmp_value=arr[0],所以从1号元素开始*/

      {

      if(arr[i]==arr[i-1]){

      tmp_count++;

      }

      else {

            /*如果当前元素与前面一个元素不相同,那么当前元素

            肯定是第一次出现。

            所以有下面的tmp_count=1;

            */

            if(tmp_count>*mostRepeatedCount)

            {

               *mostRepeatedCount=tmp_count;

               *mostRepeatedEle=tmp_value;

            }

            tmp_count=1;

            tmp_value=arr[i];

      }

      }

      /*循环结束之后仍然需要判断一次,因为有可能 最后几个元素

      全部相同,然后循环中的else就不会执行,即不会更新

      *mostRepeatedEle

      */

      if(tmp_count>*mostRepeatedCount){

      *mostRepeatedCount=tmp_count;

       *mostRepeatedEle=tmp_value;

      }

  }

  -------------------------------------------------

(方法二):循环嵌套查找:O(n^2)

void mostRepeatedElement(int *array,int length,int *mostRepeatedEle,

                            int * mostRepeatedCount){

/*初始时 *mostRepeatedEle=array[0]

*mostRepeatedCount=1;

*/

        int count;

        for(int i=0;i<length;i++){

          count=0;/*count记录的是当前元素arr[i]出现的次数*/

          for(int j=0;j<length;j++){

                if(array[i]==array[j]){

                count++;

                }

          }

          if(*mostRepeatedCount<count){

          *mostRepeatedCount=count;

          *mostRepeatedEle=array[i];

          }

        }

        }

 -------------------------------------------------

       

(方法三)hashTable : O(n)

大概思路:

/*

hashTable中的key-value记录的 是元素的值

以及出现的 次数。

*/

 HashMap<Integer,Integer> hm=new HashMap<Integer, Integer>();  

        for(int i=0;i<arr.length;i++){  

            if(hm.containsKey(arr[i])) {  

                int count=hm.get(arr[i]);  

                 hm.put(arr[i], ++count);  

             }else{  

                 hm.put(arr[i],1);  

             }  

         } 

    /*接下来从hashTable中获取count最大的值,也是只需要O(n)*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息