[leetcode]347. Top K Frequent Elements

Given a non-empty array of integers, return the?k?most frequent elements.

For example,
Given?[1,1,1,2,2,3]?and k = 2, return?[1,2].

Note:?

  • You may assume?k?is always valid, 1 ≤?k?≤ number of unique elements.
  • Your algorithm's time complexity?must be?better than O(n?log?n), where?n?is the array's size.

Subscribe?to see which companies asked this question

?

Solution:

1.使用hashtable獲取每個元素出現的次數

2.使用小根堆heap排序(priority queue實現),獲取前K個出現次數最多的元素pair

3.輸出,注意是小根堆,要reverse一下

時間復雜度:O(N * logK)

 1 class CompareDist
 2 {
 3 public:
 4     bool operator()(pair<int, int> n1, pair<int, int> n2) 
 5     {
 6         return n1.second > n2.second;
 7     }
 8 };
 9 
10 class Solution {
11 public:
12     vector<int> topKFrequent(vector<int>& nums, int k) 
13     {
14         vector<int> ret;
15         unordered_map<int, int> htable;
16         
17         for (int key : nums) // get each key appears times
18             htable[key]++;
19 
20         priority_queue<pair<int, int>, vector<pair<int, int> >, CompareDist> sheap; // use min heap to get k biggest
21         for (auto elem : htable)
22         {
23             if (sheap.size() < k)
24             {
25                 sheap.push(elem);
26             }
27             else
28             {
29                 pair<int, int> heap_min = sheap.top();
30                 if (elem.second > heap_min.second)
31                 {
32                     sheap.pop();
33                     sheap.push(elem);
34                 }
35             }
36         }
37         
38         while (!sheap.empty())
39         {
40             pair<int, int> heap_min = sheap.top();
41             ret.push_back(heap_min.first);
42             sheap.pop();
43         }
44         reverse(ret.begin(), ret.end());
45         
46         return ret;
47     }
48 };

?

或者直接使用make_heap操作,時間復雜度O(N + KlogN) = O(N)

 1 vector<int> topKFrequent(vector<int>& nums, int k) 
 2     {
 3         unordered_map<int, int> htable;
 4         for (auto &n : nums) 
 5             htable[n]++;
 6 
 7         vector<pair<int, int>> heap;
 8         for (auto &i : htable) 
 9             heap.push_back({i.second, i.first});
10 
11         vector<int> result;
12         make_heap(heap.begin(), heap.end());
13         while (k--) 
14         {
15             result.push_back(heap.front().second);
16             pop_heap(heap.begin(), heap.end());
17             heap.pop_back();
18         }
19         return result;
20     }

?

轉載于:https://www.cnblogs.com/ym65536/p/5537052.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/287560.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/287560.shtml
英文地址,請注明出處:http://en.pswp.cn/news/287560.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

合并Spark社區代碼的正確姿勢

原創文章&#xff0c;轉載請保留出處 最近剛剛忙完Spark 2.2.0的性能測試及Bug修復&#xff0c;社區又要發布2.1.2了&#xff0c;國慶期間剛好有空&#xff0c;過了一遍2.1.2的相關JIRA&#xff0c;發現有不少重要修復2.2.0也能用上&#xff0c;接下來需要將有用的PR合到我們內…

.NET 中 GC 的模式與風格

垃圾回收&#xff08;GC&#xff09;是托管語言必備的技術之一。GC 的性能是影響托管語言性能的關鍵。我們的 .NET 既能寫桌面程序 (WINFROM , WPF) 又能寫 web 程序 (ASP.NET CORE)&#xff0c;甚至還能寫移動端程序。。。不同使用場景的程序對 GC 的風格也有不同的要求&#…

(轉)java中的 | ^ 分別是什么?

|是按位或 ^是按位抑或 &是按位與比如有兩個數 int x 5;int y 11;System.out.println(x|y);System.out.println(x&y);System.out.println(x^y);結果是15&#xff0c; 1 &#xff0c;14 過程 x5 (0101二進制) y11(1011二進制) x|y 1111 15 x&y 0001 1 x…

[python opencv 計算機視覺零基礎到實戰] 七、邏輯運算與應用

一、學習目標 了解opencv中圖像的邏輯運算了解opencv中邏輯運算的應用 目錄 [python opencv 計算機視覺零基礎到實戰] 一、opencv的helloworld [【python opencv 計算機視覺零基礎到實戰】二、 opencv文件格式與攝像頭讀取] 一、opencv的helloworld [[python opencv 計算機…

Android之如何判斷當前是阿拉伯布局的方法

1 問題 判斷當前是不是阿拉伯布局的方法 2 幾種判斷方法 @SuppressLint("NewApi")public static boolean isLayoutRtl(View view, Resources res) {if (res == null || view == null) return false;Locale curLocale = res.getConfiguration().locale;//如果當前語言…

【ArcGIS風暴】數字化實驗:數據采集與編輯完整操作流程

一.實驗平臺:ArcGIS 9.3 二.實驗目的:對甘肅省的十四個地級市進行圖像配準、數據采集。 三.實驗要求:掌握地理數據采集方法,圖像配準及坐標投影,選擇主要的點、線、面進行投影。 四.實驗數據:甘肅省統計數據,甘肅省行政區劃圖。 (一).影像配準 第一步:加載…

loadrunner java 參數化_LoadRunner 參數化詳解

LoadRunner&#xff0c;是一種預測系統行為和性能的負載測試工具。通過以模擬上千萬用戶實施并發負載及實時性能監測的方式來確認和查找問題&#xff0c;LoadRunner能夠對整個企業架構進行測試。通過使用 LoadRunner&#xff0c;企業能最大限度地縮短測試時間&#xff0c;優化性…

Android之實現RTL的ViewPager

1 問題 如何實現RTL的ViewPager,就是滑動方向和我們之前滑動的方向相反,比如一般,我們用ViewPager滑動4個圖片,依次順序是 1 2 3 4 ,我們在頁面1的時候,我們一般都是習慣向左滑動到2,現在需要實現手指向右滑動到2. 2 解決辦法 1)我們可以使用ViewPager2,這個是可以支…

Why Apache Spark is a Crossover Hit for Data Scientists [FWD]

Spark is a compelling multi-purpose platform for use cases that span investigative, as well as operational, analytics. Data science is a broad church. I am a data scientist — or so I’ve been told — but what I do is actually quite different from what oth…

Blazor University (21)使用 RenderFragments 模板化組件 —— 傳遞占位符

原文鏈接&#xff1a;https://blazor-university.com/templating-components-with-renderfragements/passing-placeholders-to-renderfragments/將占位符傳遞給 RenderFragments源代碼[1]說明&#xff1a;此頁面的靈感來自用戶 ?ister?agoo 的 Twitter 帖子。首先&#xff0c…

物聯網(車聯網)平臺架構方案

技術支持QQ&#xff1a;787728951、車載終端網關采用mina/nettyspring架構&#xff0c;獨立于其他應用&#xff0c;主要負責維護接入終端的tcp鏈接、上行以及下行消息的解碼、編碼、流量控制&#xff0c;黑白名單等安全控制&#xff0c;網關同時支持交通部JT/T808-2011、JT/T80…

[python opencv 計算機視覺零基礎到實戰] 八、ROI泛洪填充

一、學習目標 了解什么是ROI了解floodFill的使用方法 如有錯誤歡迎指出~ 目錄 [python opencv 計算機視覺零基礎到實戰] 一、opencv的helloworld [【python opencv 計算機視覺零基礎到實戰】二、 opencv文件格式與攝像頭讀取] 一、opencv的helloworld [[python opencv 計…

【經典回放】JavaScript學習詳細干貨筆記之(二)

【經典回放】JavaScript學習詳細干貨筆記之(一) 【經典回放】JavaScript學習詳細干貨筆記之(二) 【經典回放】JavaScript學習詳細干貨筆記之(三) 一、JavaScript 數組 JavaScript數組的定義、使用都是非常簡單的,從a17.htm就可以知道,僅僅定義的話,就使用: var …

java string類api_java基礎—String類型常用api

1、字符串比較equalsequalsIgnoreCase 忽略大小寫做比較2、字符串拆分(切片)splitString a "lemon:python:Java";//split切片之后的結果是一個一維字符串類型數組String[] arr a.split(":");for(int i 0 ;i System.out.println(arr[i]);}3、字符串截取…

解決沖突

人生不如意之事十之八九&#xff0c;合并分支往往也不是一帆風順的。 準備新的feature1分支&#xff0c;繼續我們的新分支開發&#xff1a; $ git checkout -b feature1 Switched to a new branch feature1修改readme.txt最后一行&#xff0c;改為&#xff1a; Creating a new …

Android之java.lang.OutOfMemoryError: Failed to allocate a ** byte allocation with **free bytes and 2M

1 問題 glide加載圖片出現oom java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM 2 解決辦法 1) 簡單粗暴點的在AndroidManifest.xml添加如下&#xff0c;增大安卓虛擬機內存 android:largeHeap"…

HQL入門學習

2019獨角獸企業重金招聘Python工程師標準>>> package myHibernate; /** 測試簡單的HQL語句* 2010年4月9日 23:36:54* */ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.uti…

Oracle精簡客戶端配置

2019獨角獸企業重金招聘Python工程師標準>>> 由于Oracle client體積很大。而且安裝后&#xff0c;基本上就用2個功能&#xff1a;TNS配置服務名和SQL*Plus。下面是一種小巧、快捷的Oracle客戶端配置方法&#xff1a; 1.下載Instant Client 下載地址&#xff1a; htt…

【經典回放】JavaScript學習詳細干貨筆記之(三)

【經典回放】JavaScript學習詳細干貨筆記之(一) 【經典回放】JavaScript學習詳細干貨筆記之(二) 【經典回放】JavaScript學習詳細干貨筆記之(三) 一、再次從var開始說起 var到底是什么? 在前面的所有介紹中, JavaScript的var變量說明、是非常令人迷惑的事情。 var中…

WinUI遷移到.NET MAUI個人體驗

遷移的初衷本人平時是做.net相關的工作&#xff0c;對于.net技術棧也有一些了解&#xff0c;自從新的.net能夠跨平臺之后&#xff0c;之前也有跨平臺的ui框架Xamarin&#xff0c;現在微軟推出了.NET MAUI這個說是 統一了開發體驗&#xff0c;而且都RC版本了&#xff0c;所以本人…