取出數組中重複最多的數

來源:互聯網
上載者:User

標籤:return   print   排序   取出   返回   ash   ret   判斷   value   

思路:把數組中的每個元素作為key存到map中 如果map沒有value 設為1
有則value+1
然後用類似於選擇排序的演算法取出value 最大的那個value 的key即可

import java.util.HashMap;import java.util.Iterator;import java.util.Map;/**利用map key唯一性 唯一來儲存數組的原數,而每遍曆map中判斷出已有key(即已有相同元素)存在,則key對應的value+1*若沒有,則把元素設為key,value設為1*/public class Test_plus {    public static int findMostFrequentInArray(int[] a) {        int result = 0;        int size = a.length;        if(size==0)            return Integer.MAX_VALUE;        Map<Integer,Integer>m=new HashMap<Integer,Integer>();        //開始遍曆數組,往map中設定數組中每個元素(對應map中的key)對應出現的次數(對應map中的value)        for(int i=0;i<size;i++) {            if(m.containsKey(a[i])) {                m.put(a[i], m.get(a[i])+1);            }            else {                m.put(a[i], 1);            }        }        int most=0;        Iterator iter = m.entrySet().iterator();        //開始遍曆 比較map中每個key對應的value,取最大值,返回        while(iter.hasNext()) {            Map.Entry entry = (Map.Entry) iter.next();            int key=(Integer)entry.getKey();            int val=(Integer)entry.getValue();            if(val>most) {                result=key;                most=val;            }        }        return result;    }    public static void main(String[] args) {        int[] array= {1,5,4,3,4,4,5,4,5,5,6,6,6,6,6};        int maxFrequenceNum=findMostFrequentInArray(array);        System.out.println(maxFrequenceNum);    }}

取出數組中重複最多的數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.