美文网首页
从字符串数组中找出出现次数最多的字符串,要求时间复杂度不得大于O

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

作者: 大黑跟小白的日常 | 来源:发表于2020-11-15 09:45 被阅读0次

代码如下

    // 从字符串数组中找出出现次数最多的字符串,要求时间复杂度不得大于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;
    }

相关文章

网友评论

      本文标题:从字符串数组中找出出现次数最多的字符串,要求时间复杂度不得大于O

      本文链接:https://www.haomeiwen.com/subject/lwfnbktx.html