Pagini recente » Cod sursa (job #1881427) | Cod sursa (job #2438434) | Cod sursa (job #2273966) | Cod sursa (job #330628) | Cod sursa (job #2548692)
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
pair<int, int> qs(vector<int>& nums, int lt, int rt) {
int i = lt, j = rt;
int pos_pivot = lt + rand() % (rt - lt + 1);
int pivot = nums[pos_pivot];
while (i <= j) {
while (nums[i] < pivot) {
i++;
}
while (nums[j] > pivot) {
j--;
}
if (i <= j) {
swap(nums[i], nums[j]);
i++;
j--;
}
}
return make_pair(i, j);
}
void nth_el(vector<int>& nums, int k, int lt, int rt) {
if (lt == rt) {
return;
}
pair<int, int> p;
p = qs(nums, lt, rt);
int pos_i = p.first;
int pos_j = p.second;
if (pos_j >= k && lt < pos_j) {
nth_el(nums, k, lt, pos_j);
} else if (pos_i <= k && pos_i < rt) {
nth_el(nums, k, pos_i, rt);
}
}
int majorityElement(vector<int>& nums, int k) {
nth_el(nums, k, 0, nums.size() - 1);
return nums[nums.size() / 2];
}
};
int main() {
ifstream cin("sdo.in");
ofstream cout("sdo.out");
int n;
cin >> n;
int k;
cin >> k;
k--;
vector<int> v;
for (int i = 1, nr; i <= n; i++) {
cin >> nr;
v.push_back(nr);
}
Solution sol;
int nr = sol.majorityElement(v, k);
cout << v[k] << '\n';
return 0;
}