给定一个字符串数组,再给定整数k,请返回出现次数前k名的字符串和对应的次数

import java.util.*;
public class Solution {
    public String[][] topKstrings (String[] strings, int k) {
        if(strings==null || strings.length==0){
            return null;
        }  
        HashMap map = new HashMap();
        for(String s : strings){

            map.put(s,map.getOrDefault(s,0)+1);
        }
        PriorityQueue minHeap = new PriorityQueue();
        for(Map.Entry entrySet : map.entrySet()){
            Node node = new Node(entrySet.getKey(),entrySet.getValue());
            if(minHeap.size() < k){
                minHeap.add(node);
            }else{

                if(minHeap.peek().compareTo(node) < 0){
                    minHeap.poll();
                    minHeap.add(node);
                }
            }
        }
        
        String[][] result = new String[k][2];
        for(int i=k-1;i>=0;i--){
            Node node = minHeap.poll();
            result[i][0] = node.name;
            result[i][1] = String.valueOf(node.count); 
        }
        return result;
    }
    
    class Node implements Comparable{
        
        String name;
  
        int count;
        
        public Node(String name,int count){
            this.name = name;
            this.count = count;
        }
        
        @Override
        public int compareTo(Node node){
            if(this.count > node.count){
                return 1;
            }else if(this.count < node.count){
                return -1;
            }else{
                return node.name.compareTo(this.name);
            }
        }
    }
}

你可能感兴趣的:(java)