要点: 使用Map的key来计数,实现复杂度为 n 的算法
private static int findMajorityNum(int[] numbers) throws Exception {
int length=numbers.length;
HashMap<Integer,Integer>map=new HashMap<Integer,Integer>();
for (int number : numbers) {
if (map.containsKey( number )) {
map.put( number, map.get( number ) + 1 );
} else {
map.put( number, 1 );
}
}
for (int number : numbers) {
if (map.get( number ) > length / 2) {
return number;
}
}
throw new java.lang.Exception("no such specific number in this array");
}
public static void main(String[] args) {
try {
System.out.println( findMajorityNum( new int[]{2, 5, 3, 5, 5, 2, 5, 4, 5} ));
} catch (Exception e) {
e.printStackTrace();
}
}