2011-01-21 89 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)]++; 
} 

然后在计数找到最大的项目[]

相关问题