leetcode(c++)topK
#include <iostream> #include <queue> #include <vector> #include <unordered_map> using namespace std; bool cmp(const pair<int,int>&p1,const pair<int,int>&p2) { return p2.second - p1.second; } vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int,int>map; vector<int>res{}; for(int i = 0; i < nums.size(); ++i) { ++map[nums[i]]; } vector<pair<int,int>>v; for(auto m:map) { v.emplace_back(m); } sort(v.begin(),v.end(),cmp); for(int i = 0; i < k ; ++i) { res.emplace_back(v[i].first); } return res; } void print(const vector<int>& v) { for(int num : v) { cout << num << " "; } cout << endl; } vector<int>sortColor(const vector<int>&corlors) { unordered_map<int,int>map; vector<int>res{}; int zero = 0, one = 0 ,two = 0; for(int i = 0; i < corlors.size(); ++i) { if(0 == corlors[i])++zero; if(1 == corlors[i])++one; if(2 == corlors[i])++two; } cout << zero << " " << one << " " << two << endl; int i = 0; while(i < zero) { res.emplace_back(0); ++i; } for(int i = zero; i < zero + one; ++i) { res.emplace_back(1); } for(int i = zero+one;i < corlors.size(); ++i) { res.emplace_back(2); } return res; } int partition(vector<int>& a, int l, int r) { int x = a[r], i = l - 1; for (int j = l; j < r; ++j) { if (a[j] <= x) { swap(a[++i], a[j]); } } swap(a[i + 1], a[r]); return i + 1; } int randomPartition(vector<int>& a, int l, int r) { int i = rand() % (r - l + 1) + l; swap(a[i], a[r]); return partition(a, l, r); } int quickSelect(vector<int>& a, int l, int r, int index) { int q = randomPartition(a, l, r); if (q == index) { return a[q]; } else { return q < index ? quickSelect(a, q + 1, r, index) : quickSelect(a, l, q - 1, index); } } int findKthLargest(vector<int>& nums, int k) { srand(time(0)); return quickSelect(nums, 0, nums.size() - 1, nums.size() - k); } int main() { vector<int>input{1,1,1,2,2,3}; //LeetCode347 auto res = topKFrequent(input,2); print(res); //LeetCode75 vector<int>input1{0,0,0,2,1,1}; auto res0 = sortColor(input1); print(res0); //LeetCode215 vector<int>input2{1,3,4,5,6}; cout << findKthLargest(input2,2) << endl; return 0; }