题解 | #序列和#

字符串出现次数的TopK问题

http://www.nowcoder.com/practice/fd711bdfa0e840b381d7e1b82183b3ee

import java.util.*;


public class Solution {
    /**
     * return topK string
     * @param strings string字符串一维数组 strings
     * @param k int整型 the k
     * @return string字符串二维数组
     */
    public String[][] topKstrings (String[] strings, int k) {
        // write code here
        // 15:11
        TreeMap<String,Integer> map = new TreeMap<>();
        for(int i=0;i<strings.length;i++){
            map.put(strings[i],map.getOrDefault(strings[i],0)+1);
        }
        // 排序
        ArrayList<Map.Entry<String,Integer>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list,new Comparator<Map.Entry<String,Integer>>(){
            @Override
            public int compare(Map.Entry<String,Integer> o1,Map.Entry<String,Integer> o2){
                if(o1.getValue().equals(o2.getValue())){
                    return o1.getKey().compareTo(o2.getKey());
                }else{
                    return o2.getValue().compareTo(o1.getValue());
                }
            }
        });

        String[][] res = new String[k][2];

        for(int i=0;i<k;i++){
            res[i][0] = new String(list.get(i).getKey());
            res[i][1] = new String(String.valueOf(list.get(i).getValue()));
        }
        return res;
    }
}

这是借用treeMap的排序做的,不知道算不算?

全部评论

相关推荐

11-11 11:35
已编辑
字节跳动_字节hr
“面试官好,我之前在字节跳动实习过……”“您说的是字节跳动?”原本在低头圈画简历的三位面试官瞬间停了手,握着的笔顿在半空,会议室里只有键盘余温散出的微弱声响,都变得格外清晰。“就是那个靠算法推荐,把短视频和资讯信息流做到顶流的字节跳动?”我微微颔首,保持着平稳的语气:“嗯,主要在抖音后端研发团队实习,负责用户行为埋点链路优化、推荐策略效果迭代的工程落地,参与过流量峰值容灾方案设计和线上故障排查,把接口响应耗时压到了毫秒级。”其中一位面试官身体前倾,声音都亮了几分:“天啊!是那个做出抖音、TikTok,还把飞书、剪映做到行业标杆的字节跳动?”另一位面试官手忙脚乱摸出手机:“不好意思,我先拍个抖音,刚好想发条‘面到字节实习生’的动态蹭波流量。”话还没落地,最后一位面试官已经把一份写满薪资数字的&nbsp;offer&nbsp;意向书推到我面前:“现在就能签吗?股票期权随便谈,级别我们直接给你定到&nbsp;P6!”我抬眼扫过三人,礼貌而从容地回应:“Thank&nbsp;you&nbsp;very&nbsp;much&nbsp;for&nbsp;the&nbsp;offer.&nbsp;I&nbsp;still&nbsp;need&nbsp;to&nbsp;compare&nbsp;different&nbsp;opportunities,&nbsp;and&nbsp;I’ll&nbsp;get&nbsp;back&nbsp;to&nbsp;you&nbsp;once&nbsp;I’ve&nbsp;made&nbsp;my&nbsp;decision.”说完,我合上桌边一本印着&nbsp;“ByteDance”&nbsp;蓝色&nbsp;logo&nbsp;的笔记本,微笑点头后离开了会议室。走到走廊尽头时,我忍不住轻叹了口气:“唉,手里的&nbsp;offer&nbsp;都堆不下了,到底选哪个好呢?要是字节的技术口碑没这么硬就好了。”都看到这里了&nbsp;不投一下吗【字节跳动-校园招聘】内推链接:https://job.toutiao.com/s/KTaYC1Kvckg,内推码:MNW17D7。心脏和字节一起等你跳动~~~(通过此链接投递计入内推,内推简历优先筛选~)参考文献[1]&nbsp;&quot;老师好,我之前在蚂蚁集团实习过&quot;,&nbsp;国家一级产品交付工程师.[2]&nbsp;“面试官好,我之前在拼多多集团实习过……”,I_can_do_better.作者:I_can_do_better链接:https://www.nowcoder.com/来源:牛客网
投递字节跳动等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务