给定一堆区间,对于每一个区间,找出左端点 ≥ 这个区间的右端点的一个区间(并且左端点尽量小)。
思路
给区间起点排序,然后对每一个区间,我们二分查找一下满足条件的区间即可。
代码
/**
* Definition for an interval.
*
struct Interval {
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
};
*/
struct node {
Interval x;
int pos;
node(Interval a, int b) : x(a), pos(b) {
}
};
bool cmp (node *a, node* y) {
if ((a->x).start != (y->x).start) return (a->x).start < (y->x).start;
return (a->x).end < (y->x).end;
}
class Solution {
public:
vector<int> findRightInterval(vector<Interval>& intervals) {
int i = 0;
vector<node*> a;
vector<int> ans(intervals.size(), -1);
for (auto x : intervals) {
node *t = new node(x, i++);
a.push_back(t);
}
sort(a.begin(), a.end(), cmp);
for (int i = 0; i < a.size(); i++) {
Interval t = a[i]->x;
int ed = t.end;
int L = i + 1, R = a.size() - 1, M = -1;
while (L < R) {
M = L + (R - L >> 1);
if ((a[M]->x).start < ed) L = M + 1;
else R = M;
}
ans[a[i]->pos] = (a[R]->x).start >= ed ? a[R]->pos : -1;
}
return ans;
}
};