2011-01-21 90 views
0

以下s代碼到 查找number.wat中給定數字的出現次數我應該這麼做才能找到數字發生在一個給定數量最多的。(我應該創建陣列並保存這些值,然後進行比較) 誰能請幫助我..最常出現的數字的數量......找出給定數字中出現次數最多的數字

import java.util.*; 
public class NumOccurenceDigit 
{ 
    public static void main(String[] args) 

     { 
      Scanner s= new Scanner(System.in); 

      System.out.println("Enter a Valid Digit.(contaioning only numerals)"); 
      int number = s.nextInt(); 
      String numberStr = Integer.toString(number); 
      int numLength = numberStr.length(); 

      System.out.println("Enter numer to find its occurence"); 
      int noToFindOccurance = s.nextInt(); 
      String noToFindOccuranceStr = Integer.toString(noToFindOccurance); 
      char noToFindOccuranceChar=noToFindOccuranceStr.charAt(0); 

      int count = 0; 
      char firstChar = 0; 
      int i = numLength-1; 
      recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr); 

    } 
    static void recFunNumOccurenceDigit(char firstChar,int count,int i,char noToFindOccuranceChar,String numberStr) 
    { 

     if(i >= 0) 
     { 
      firstChar = numberStr.charAt(i); 
      if(firstChar == noToFindOccuranceChar) 
      //if(a.compareTo(noToFindOccuranceStr) == 0) 
      { 
       count++; 

      } 
      i--; 
      recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr); 
     } 
     else 
     { 
      System.out.println("The number of occurance of the "+noToFindOccuranceChar+" is :"+count); 
      System.exit(0); 
     } 
    } 
} 


/* 
* Enter a Valid Digit.(contaioning only numerals) 
456456 
Enter numer to find its occurence 
4 
The number of occurance of the 4 is :2*/ 

回答

2
O(n) 
  1. 保持int digits[] = new int[10];
  2. 每次遭遇的digits[i]++
  3. digit i增加值返回數字陣列及其指數最大。就這樣。

這裏是我的Java代碼:

public static int countMaxOccurence(String s) { 
    int digits[] = new int[10]; 

    for (int i = 0; i < s.length(); i++) { 
     int j = s.charAt(i) - 48; 
     digits[j]++; 
    } 

    int digit = 0; 
    int count = digits[0]; 
    for (int i = 1; i < 10; i++) { 
     if (digits[i] > count) { 
      count = digits[i]; 
      digit = i; 
     } 
    } 

    System.out.println("digit = " + digit + " count= " + count); 
    return digit; 
} 

這裏有一些測試

System.out.println(countMaxOccurence("12365444433212")); 
System.out.println(countMaxOccurence("1111111")); 
2

聲明計數[]數組

,改變你找到像

//for (i = 1 to n) 
{ 
    count[numberStr.charAt(i)]++; 
} 

然後在計數找到最大的項目[]

相關問題