Commit ec61268b authored by yaozc's avatar yaozc
Browse files

keep going

parent 6540bf0a
~$etcode总结.docx
......@@ -1312,17 +1312,107 @@ public:
Kth Largest Element in an Array
// Selection sort 典型的运用,
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
for(int outer=0; outer<nums.size(); outer++){
int max_pos = outer;
for(int inner=outer; inner<nums.size(); inner++){
if(nums[max_pos]<nums[inner]) max_pos = inner;
}
if(outer==k-1) return nums[max_pos];
swap(nums[outer], nums[max_pos]);
}
return -1;
}
};
Top K Frequent Elements
//第一次用priority_queue。。。。当pq只考虑最大的top时,complexity为 O(1),所以合适
//考虑过用map<int, int>但map不支持多个相同frequency的出现呀!所以不能用!(一个key出现一次)
//老规矩,要计数的就用 hash table!好用!
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
// build the freq table
unordered_map<int, int> hash;
for(auto &num: nums) hash[num]++;
//build the frequency table
priority_queue<pair<int, int>> pq;
for(auto it=hash.begin(); it != hash.end(); it++){
pq.push(make_pair(it->second, it->first));
}
vector<int> 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<double, int> &a, pair<double, int> &b) {
return a.first > b.first;
}
};
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
priority_queue<pair<double, int>, vector<pair<double, int>>, compare > pq;
for(int i=0; i<points.size(); i++){
double dist = (0-points[i][0]) * (0-points[i][0]) + (0-points[i][1]) * (0-points[i][1]);
pq.push(make_pair(dist, i));
}
vector<vector<int>> res;
while(K>0){
K--;
int index = pq.top().second;
pq.pop();
res.push_back(points[index]);
}
return res;
}
};
// solution2
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
priority_queue<pair<double, int>> pq;
for(int i=0; i<points.size(); i++){
double dist = (0-points[i][0]) * (0-points[i][0]) + (0-points[i][1]) * (0-points[i][1]);
pq.push(make_pair(dist, i));
if(pq.size()>K) pq.pop();
}
vector<vector<int>> 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