题解 | #求二叉树的层序遍历#

字符串出现次数的TopK问题

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

使用map存放相关的字符串和计数  
然后使用list 对map的entry进行排序  取出前k个就可以了;



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
        Map<String,Integer> map=new HashMap<String,Integer>();
        for(String str: strings){
             map.put(str,map.getOrDefault(str,0)+1);
        }
        List<Map.Entry<String,Integer>> infos = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
        Collections.sort(infos, new Comparator<Map.Entry<String,Integer>>(){
            public int compare(Map.Entry<String,Integer> str1, Map.Entry<String,Integer> str2) {
                if(str1.getValue()==str2.getValue()) return str1.getKey().compareTo(str2.getKey());
                else return str2.getValue()-str1.getValue();
            }
        });
        String[][] topKstrings=new String[k][2];
        int c=0;
        for(Map.Entry<String,Integer> entry:infos){
            String num = String.valueOf(entry.getValue());
            topKstrings[c][0]=entry.getKey();
            topKstrings[c][1]=num;
            c++;
            if(c==k){
                break;
            }
        }
        return topKstrings;
    }
}
全部评论

相关推荐

买蜜雪也用卷:我觉得应该没有哪个人敢说自己熟练使用git,代码分支一复杂还是得慢慢寻思一下的,不过基本的拉代码提交代码还有分支什么的是应该会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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