我需要以下问题的帮助: http://practiceit.cs.washington.edu/problem.jsp?category=Building+Java+Programs%2C+3rd+edition%2FBJP3+Chapter+11&problem= bjp3-11-e19-最稀有的
这是我的代码:
public static int rarest(Map<String, Integer> m) {
if ( m.isEmpty() ) {
throw new NullPointerException();
}
int min = Integer.MAX_VALUE;
int store = Integer.MAX_VALUE;
Map<Integer, Integer> m1 = new TreeMap<Integer, Integer>();
List<Integer> l = new ArrayList<Integer>();
for (Integer a: m.values()) {
l.add(a);
}
for(int i=0; i<l.size(); i++) {
int temp = 1;
for(int j=i+1; j<l.size(); j++) {
if ( l.get(i) == l.get(j) ) {
temp++;
}
}
if ( !m1.containsKey(l.get(i)) ) {
m1.put( l.get(i), temp );
}
}
for(Integer a: m1.keySet()) {
int val = m1.get(a);
if (val == min) {
if ( a<store ) {
store = a;
}
} else if ( val < min ) {
min = val;
store = a;
}
}
return store;
}
当代码在此运行时:
{A=1000, B=1, C=101, D=3, J=1000, K=101, L=3, LN=1, M=1000, N=101, R=3, S=1000, T=101, V=3, W=1, X=1, Y=1, Z=1},
我得到了回报1000
,应该什么时候回报3
。为什么会这样?