Skip to content

Commit b7d3df5

Browse files
authored
randomized-select
1 parent f25a07e commit b7d3df5

File tree

1 file changed

+38
-57
lines changed

1 file changed

+38
-57
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,47 @@
1-
/*************************************************************************
2-
> File Name: randomized-select.cpp
3-
> Author: Louis1992
4-
5-
> Blog: http://gzc.github.io
6-
> Created Time: Sun May 24 11:46:39 2015
7-
************************************************************************/
81
#include<iostream>
92
#include<vector>
103
using namespace std;
114

12-
class Solution {
13-
14-
int kthSmallest(vector<int>& arr, int l, int r, int k)
15-
{
16-
17-
if (k > 0 && k <= r - l + 1)
18-
{
19-
int pos = randomPartition(arr, l, r);
20-
21-
if (pos-l == k-1)
22-
return arr[pos];
23-
else if(pos-l > k-1)
24-
return kthSmallest(arr, l, pos-1, k);
25-
else
26-
return kthSmallest(arr, pos+1, r, k-pos+l-1);
27-
}
28-
return INT_MAX;
29-
}
30-
31-
int partition(vector<int>& arr, int l, int r)
32-
{
33-
int x = arr[r], i = l;
34-
for(int j = l; j <= r - 1; j++)
35-
{
36-
if (arr[j] <= x)
37-
{
38-
swap(arr[i], arr[j]);
39-
i++;
40-
}
5+
int partition(vector<int>& arr, int l, int r) {
6+
int x = arr[r], i = l;
7+
for (int j = l; j <= r - 1; j++) {
8+
if (arr[j] <= x) {
9+
swap(arr[i], arr[j]);
10+
i++;
4111
}
42-
swap(arr[i], arr[r]);
43-
return i;
44-
}
45-
46-
int randomPartition(vector<int>& arr, int l, int r)
47-
{
48-
int n = r-l+1;
49-
int pivot = rand() % n;
50-
swap(arr[l + pivot], arr[r]);
51-
return partition(arr, l, r);
5212
}
13+
swap(arr[i], arr[r]);
14+
return i;
15+
}
16+
17+
int randomPartition(vector<int>& arr, int l, int r) {
18+
int n = r - l + 1;
19+
int pivot = rand() % n;
20+
swap(arr[l + pivot], arr[r]);
21+
return partition(arr, l, r);
22+
}
5323

54-
public:
55-
int findKthLargest(vector<int>& nums, int k) {
56-
return kthSmallest(nums, 0, nums.size()-1, nums.size()-k+1);
24+
int kthSmallest(vector<int>& arr, int l, int r, int k) {
25+
int pos = randomPartition(arr, l, r);
26+
if (pos - l == k - 1) {
27+
return arr[pos];
28+
} else if (pos - l > k - 1) {
29+
return kthSmallest(arr, l, pos - 1, k);
30+
} else {
31+
return kthSmallest(arr, pos+1, r, k-pos+l-1);
5732
}
58-
};
33+
}
34+
35+
int kthSmallest(vector<int>& arr, int k) {
36+
// TODO: Validate k is in valid range.
37+
return kthSmallest(arr, 0, arr.size() - 1, k);
38+
}
5939

60-
int main()
61-
{
62-
int arr[5] = {2,4,0,-2,8};
63-
vector<int>v(arr, arr+5);
64-
Solution s;
65-
cout << s.findKthLargest(v, 2) << endl;
66-
}
40+
int main() {
41+
vector<int>v{3,4,2,5,1};
42+
cout << kthSmallest(v, 1) << endl;
43+
cout << kthSmallest(v, 2) << endl;
44+
cout << kthSmallest(v, 3) << endl;
45+
cout << kthSmallest(v, 4) << endl;
46+
cout << kthSmallest(v, 5) << endl;
47+
}

0 commit comments

Comments
 (0)