之前面试某大厂,最后的面试题就是这个;当时没有回答上来,心中一直更跟于怀;
看了别人的方法(https://www.cnblogs.com/lcy0515/p/10807853.html),赶紧好麻烦。想自己弄一个
import com.sun.xml.internal.bind.v2.TODO; import java.util.*; public class TopK { public static void main(String arg[]){ String[] str=new String[]{"AAA","BBB","CCC","AAA","BBB","AAA"}; //取出所有的字符串,去重,存入list List<String> list = new LinkedList<String>(); for(int i = 0; i < str.length; i++) { if(!list.contains(str[i])) { list.add(str[i]); //System.out.println(list.get(i)); } } int k = 0; //计算出字符串的出现的次数 HashMap<String,Integer> hashMap = new HashMap<String, Integer>(); for(int i = 0; i < list.size(); i++) { for(int j = 0;j< str.length;j++){ if (list.get(i).equals(str[j])){ k++; } } hashMap.put(list.get(i),k); k = 0; } //System.out.println(hashMap); //对名称进行排序,首先要得到HashMap中键的集合(keySet),并转换为数组,这样才能用Arrays.sort()进行排序 Set set=hashMap.keySet(); Object[] arr=set.toArray(); Arrays.sort(arr); for(Object key:arr){ System.out.println(key); } System.out.println(arr[1-1]); //输出第一个 } }
参考文档:https://blog.csdn.net/xHibiki/article/details/82938480?utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control
原文:https://www.cnblogs.com/perfect11a/p/14723051.html