[Leetcode][第347题][JAVA][前K个高频元素][优先队列][堆][遍历set/map]
生活随笔
收集整理的這篇文章主要介紹了
[Leetcode][第347题][JAVA][前K个高频元素][优先队列][堆][遍历set/map]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【問題描述】[中等]
【解答思路】
1. 堆
復雜度
【總結】
1. 大小堆的建立(其他類比)
1.1 Map的小堆
PriorityQueue queue = new PriorityQueue<>((a,b)->map.get(a)-map.get(b));
1.2 Map的大堆
//idea Comparator 自動生成 PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {@Overridepublic int compare(Integer a, Integer b) {return map.get(b) -map.get(a);}});1.3 分開寫
// Customer 一個class 含id 7 初始化大小 Queue<Customer> customerPriorityQueue = new PriorityQueue<>(7, idComparator); //匿名Comparator實現public static Comparator<Customer> idComparator = new Comparator<Customer>(){@Overridepublic int compare(Customer c1, Customer c2) {return (int) (c1.getId() - c2.getId());}};2.遍歷map /set
map
public static void main(String[] args) {// 構建一個Map 初始值為3條數據Map<String, String> map = new HashMap<String, String>();map.put("1", "xiaqiu");map.put("2", "pangzi");map.put("3", "shouzi");//第一種:普遍使用,二次取值System.out.println("通過Map.keySet遍歷key和value:");for (String key : map.keySet()) {System.out.println("key= "+ key + " and value= " + map.get(key));}//第二種:通過Iterator迭代器遍歷循環Map.entrySet().iterator();System.out.println("通過Map.entrySet使用iterator遍歷key和value:");Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();while (it.hasNext()) {Map.Entry<String, String> entry = it.next();System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());}//第三種:筆者推薦,尤其是容量大時(相對來說 比2好一點 效率高)System.out.println("通過Map.entrySet遍歷key和value");for (Map.Entry<String, String> entry : map.entrySet()) {System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());}//第四種System.out.println("通過Map.values()遍歷所有的value,但不能遍歷key");for (String v : map.values()) {System.out.println("value= " + v);}}set
1.迭代遍歷: Set<String> set = new HashSet<String>(); Iterator<String> it = set.iterator(); while (it.hasNext()) { String str = it.next(); System.out.println(str); } 2.for循環遍歷: for (String str : set) { System.out.println(str); }3.堆的思想
【數據結構與算法】堆
參考鏈接:https://www.cnblogs.com/magicya/p/6683052.html
參考鏈接:https://www.cnblogs.com/XQiu/p/5087961.html
總結
以上是生活随笔為你收集整理的[Leetcode][第347题][JAVA][前K个高频元素][优先队列][堆][遍历set/map]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jQuery缓存数据——仿Map
- 下一篇: 各省份的车牌简称 备案地区的简称