Commit ec61268b by yaozc

### keep going

parent 6540bf0a
.gitignore 0 → 100644
 ~\$etcode总结.docx
 ... @@ -1312,17 +1312,107 @@ public: ... @@ -1312,17 +1312,107 @@ public: Kth Largest Element in an Array // Selection sort 典型的运用， class Solution { public: int findKthLargest(vector& nums, int k) { for(int outer=0; outer但map不支持多个相同frequency的出现呀！所以不能用！（一个key出现一次） //老规矩，要计数的就用 hash table！好用！ class Solution { public: vector topKFrequent(vector& nums, int k) { // build the freq table unordered_map hash; for(auto &num: nums) hash[num]++; //build the frequency table priority_queue> pq; for(auto it=hash.begin(); it != hash.end(); it++){ pq.push(make_pair(it->second, it->first)); } vector res; while(k>0){ k--; res.push_back(pq.top().second); pq.pop(); } return res; } }; K Closest Points to Origin // 思路和top k frequent element 有点像 // 也是用pq解，问题在这个compator有点难写。。。。。。。。。 //solution2 用默认comparator，维护pq的size，也不失为一种方法 class Solution { struct compare { bool operator()(pair &a, pair &b) { return a.first > b.first; } }; public: vector> kClosest(vector>& points, int K) { priority_queue, vector>, compare > pq; for(int i=0; i> res; while(K>0){ K--; int index = pq.top().second; pq.pop(); res.push_back(points[index]); } return res; } }; // solution2 class Solution { public: vector> kClosest(vector>& points, int K) { priority_queue> pq; for(int i=0; iK) pq.pop(); } vector> res; while(K>0){ K--; int index = pq.top().second; pq.pop(); res.push_back(points[index]); } return res; } }; ... ...
No preview for this file type
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment