Forum

Post 03.10.2012   # 1
Subject Problem 200 - FrequentNumber

The solution of this problem is straight forward - find a way to transform and keep all the numbers.

Since the count of numbers is small, any technique for storing and retrieving will work. Most people prefered to use a map as it is quite fast to code, easy to implement and gives best performance.

As for the transformation phase, many people encoded all the possible outcomes. But there is an interesting solution that can skip this step and help you code the solution faster. This is how anikov solved this problem:

import java.util.HashMap;
import java.util.Map;
public class FrequentNumber {
  public String mostFrequentNumber(String[] inputStrings) {
    String res = "";
    int resm = 0;
    Map m = new HashMap();
    for (String s : inputStrings) {
      String z = "";
      for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        int x = (c - 'A');
        z = z + (2 + ((x - x / 17 - x / 24) / 3));
      }
      int k = 0;
      if (m.containsKey(z)) {
        k = m.get(z);
      }
      k++;
      m.put(z, k);
      if (k > resm || (k == resm && z.compareTo(res) < 0)) {
        res = z;
        resm = k;
      }
    }
    return res;
  }
}

 

palikrushev is offline Reply

Please login to post reply.