-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathFind k-th smallest element in given n ranges.cpp
43 lines (40 loc) · 1.22 KB
/
Find k-th smallest element in given n ranges.cpp
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
class Solution{
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(begin(intervals), end(intervals));
vector<int>v = intervals[0];
vector<vector<int>>ans;
for(int i = 1; i < intervals.size(); i++){
if(v[1]>=intervals[i][0]){
v[1] = max(v[1], intervals[i][1]);
}
else{
ans.push_back(v);
v = intervals[i];
}
}
ans.push_back(v);
return ans;
}
int find_kth(vector<vector<int>>&merged, int k){
int n = merged.size();
for (int j = 0; j < n; j++)
{
if (k <= abs(merged[j][1] -
merged[j][0] + 1))
return (merged[j][0] + k - 1);
k = k - abs(merged[j][1] - merged[j][0] + 1);
}
if (k)
return -1;
}
vector<int>kthSmallestNum(int n, vector<vector<int>>&range, int q, vector<int>queries){
vector<vector<int>>merged = merge(range);
vector<int>ans;
for(int i = 0 ; i < queries.size(); i++){
int res = find_kth(merged, queries[i]);
ans.push_back(res);
}
return ans;
}
};