天天看點

最大出現次數統計的關鍵算法

編寫一個程式,對使用者輸入的任意一組字元如{3,1,4,7,2,1,1,2,2},輸出其中出現次數最多的字元,并顯示其出現次數。如果有多個字元出現次數均為最大且相等,則輸出最先出現的那個字元和它出現的次數。例如,上面輸入的字元集合中,“1”和“2”都出現了3次,均為最大出現次數,因為“1”先出現,則輸出字元“1”和它出現的次數3次。

注意:使用分支、循環結構語句實作。

package seven;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
//3,1,4,7,2,1,1,2,2
public class one {
    public static void main(String[] args) {
        System.out.print("輸入一組字元串:");
        Scanner s = new Scanner(System.in);
        String n = s.nextLine();

        int[] array = new int[n.length()];

        for (int i = 0; i < n.length(); i++) {
            char sig = n.charAt(i);//将輸入的字元串拆分單個字元
            int num = Integer.parseInt(sig+"");
            array[i] = num;
        }
        System.out.println(  getMostInteger( array ) );
        s.close();
    }

    public static String getMostInteger( int[] arrayMath ){
        //key儲存出現過的數字,value儲存形式為 下标_出現次數長度的字元。
        Map<Integer,String> m = new HashMap<>();

        int max = 1;//儲存最大出現的次數
        int minIndex = 0;//儲存最大數的下标


        for( int i = 0 ; i < arrayMath.length ; i ++ ){
            if( m.containsKey( arrayMath[i] ) ){       //containsKey判斷是否存在該鍵(arrayMath[i])
                m.put( arrayMath[i] , m.get( arrayMath[i] ) + 1 );
                String[] s = m.get(arrayMath[i]).split("_");//split();是将指定字元串按某指定的分隔符進行拆分,拆分将會形成一個字元串的數組并傳回。//将索引和出現次數分離
                int length = s[1].length();//擷取出現次數
                if( length > max ){
                    max = length;
                    minIndex = Integer.parseInt(s[0]);//把()裡的内容轉換成整數

                }else if( length == max ){
                    if( Integer.parseInt( s[0] ) < minIndex ){
                        minIndex = Integer.parseInt( s[0] );
                    }
                }
            }else {
                m.put( arrayMath[i] , i + "_" + 1 );
            }
        }
        String result = "出現次數最多的是" + arrayMath[minIndex] + "出現的次數為" + max;
        return result;
    }
}
      

  

路是自己的,沒必要拿别人的标準衡量自己,它隻配成為墊腳石。