题目:
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
Example 2:
Input: nums = [1], k = 1 Output: [1]
Note:
分析:找出数组中前k多 的数
思路:需要用有序的map集合来存储,就想到了TreeMap,但是这个是基于key的排序,
而我的做法中key存的是数组中的元素,value存的是元素的个数
就希望能够按照value从大到小排序,取前k个就好了
就涉及两个问题:
https://blog.csdn.net/liuxiao723846/article/details/50454622
借助了这个博客里的内容:
TreeMap底层是根据红黑树的数据结构构建的,默认是根据key的自然排序来组织(比如integer的大小,String的字典排序)。所以,TreeMap只能根据key来排序,是不能根据value来排序的(否则key来排序根本就不能形成TreeMap)。
今天有个需求,就是要根据treeMap中的value排序。所以网上看了一下,大致的思路是把TreeMap的EntrySet转换成list,然后使用Collections.sor排序。代码:
//treeMap中的排序依然没变,变得只是装treeMap的Arraylist
public static void sortByValue() {
Map map = new TreeMap();
map.put("a", "dddd");
map.put("d", "aaaa");
map.put("b", "cccc");
map.put("c", "bbbb");
List> list = new ArrayList>(map.entrySet());
Collections.sort(list,new Comparator>() {
//升序排序
public int compare(Entry o1, Entry o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
for (Entry e: list) {
System.out.println(e.getKey()+":"+e.getValue());
}
}
改到我这里面就是:
List> t_list = new ArrayList>(map.entrySet());
Collections.sort(t_list, new Comparator>() {
@Override
public int compare(Map.Entry o1, Map.Entry o2) {
//按照value的降序排列
if(o1.getValue()>o2.getValue()) return -1;
if(o1.getValue()==o2.getValue()) return 0;
return 1;
}
});
参考代码:
https://blog.csdn.net/qq_31024823/article/details/80203448
public class Eee {
public static void main(String[] args) {
TreeMap treeMap = new TreeMap<>();
treeMap.put("s", 2);
treeMap.put("w", 3);
treeMap.put("d", 1);
treeMap.put("f", 0);
treeMap.put("h", 9);
treeMap.put("q", 11);
treeMap.put("a", 25);
//遍历1
System.out.println("======================遍历一========================");
Iterator it1 = treeMap.keySet().iterator();
while(it1.hasNext()){
String key = it1.next();
Integer value = treeMap.get(key);
System.out.println("key=" + key + " ; " + "value=" + value);
}
//遍历二
System.out.println("======================遍历二========================");
Iterator> it2 = treeMap.entrySet().iterator();
while(it2.hasNext()) {
Entry entry = it2.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("key=" + key + " ; " + "value=" + value);
}
}
}
class Solution {
public List topKFrequent(int[] nums, int k) {
List list = new ArrayList();
Map map = new TreeMap();
for(int i = 0 ;i> t_list = new ArrayList>(map.entrySet());
Collections.sort(t_list, new Comparator>() {
@Override
public int compare(Map.Entry o1, Map.Entry o2) {
if(o1.getValue()>o2.getValue()) return -1;
if(o1.getValue()==o2.getValue()) return 0;
return 1;
}
});
int i = 0;
for(Map.Entry e:t_list){
if(i