从字符串数组中找出出现次数最多的字符串,要求时间复杂度不得大于O(n)

代码如下

    // 从字符串数组中找出出现次数最多的字符串,要求时间复杂度不得大于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;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容