1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| #include <iostream> #include <vector> #include <queue> #include <algorithm> #include <tuple> using namespace std;
class Solution { public: int findKthLargest(vector<int>& nums, int k) { priority_queue<int, vector<int>, greater<int>> pq;
for (const int& num : nums) { pq.push(num); if (pq.size() > k) { pq.pop(); } } return pq.top(); } };
class Solution_1 { public: int findKthLargest(vector<int>& nums, int k) { return quickSelect(nums, 0, nums.size()-1, k-1); }
int quickSelect(vector<int>& nums, int l, int r, int k) { if (l == r) { return nums[l]; }
int pivotIndex = l + rand() % (r - l + 1); int pivot = nums[pivotIndex];
int i = l, j = r; while (i <= j) { while (i <= j && nums[i] > pivot) { i++; } while (i <= j && nums[j] < pivot) { j--; } if (i <= j) { swap(nums[i++], nums[j--]); } }
if (k <= j) { return quickSelect(nums, l, j, k); } else if (k >= i) { return quickSelect(nums, i, r, k); } else { return nums[k]; } } };
void printArray(const vector<int>& nums) { cout << "["; for (size_t i = 0; i < nums.size(); i++) { cout << nums[i]; if (i != nums.size() - 1) cout << ","; } cout << "]"; }
int main() { Solution solution; vector<vector<int>> nums_cases = { {3,2,1,5,6,4}, {3,2,3,1,2,4,5,5,6} }; vector<int> k_cases = { 2, 4 };
for (int i = 0; i < nums_cases.size(); i++) { auto& nums = nums_cases[i]; int k = k_cases[i];
cout << "Input: nums = "; printArray(nums); cout << ", k = " << k << endl; int result = solution.findKthLargest(nums, k); cout << "Output: " << result << endl; }
return 0; }
|