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

34次阅读

共计 946 个字符,预计需要花费 3 分钟才能阅读完成。

import java.util.*;
public class Solution {public String[][] topKstrings (String[] strings, int k) {if(strings==null || strings.length==0){return null;}  
        HashMap<String,Integer> map = new HashMap();
        for(String s : strings){map.put(s,map.getOrDefault(s,0)+1);
        }
        PriorityQueue<Node> minHeap = new PriorityQueue();
        for(Map.Entry<String,Integer> 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<Node>{
        
        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);
            }
        }
    }
}

正文完
 0