代码如下
// 从字符串数组中找出出现次数最多的字符串,要求时间复杂度不得大于O(n)
public static String getMostOneFrom(String[] strs) {
if (strs == null || strs.length < 1) {
throw new IllegalArgumentException("参数不合法");
}
int length = strs.length;
int mapCap = (int) (length / 0.75) + 1;
HashMap<String, Integer> frequentMap = new HashMap<>(mapCap);
// 初始化 出现最多次数的 字符串为 数组第一个字符串,出现的最多次数为1次
String mostFrequentStr = strs[0];
Integer mostTimes = 1;
for (int i = 0; i < strs.length; i++) {
Integer times = frequentMap.get(strs[i]);
if (times == null) {
times = 1;
} else {
times++;
}
frequentMap.put(strs[i], times);
if(times > mostTimes) {
mostFrequentStr = strs[i];
mostTimes = times;
}
}
return mostFrequentStr;
}