Skip to content

Commit 1eaef82

Browse files
authored
Create find-right-interval.cpp
1 parent 4f21e6c commit 1eaef82

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

C++/find-right-interval.cpp

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Time: O(nlogn)
2+
// Space: O(n)
3+
4+
/**
5+
* Definition for an interval.
6+
* struct Interval {
7+
* int start;
8+
* int end;
9+
* Interval() : start(0), end(0) {}
10+
* Interval(int s, int e) : start(s), end(e) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
vector<int> findRightInterval(vector<Interval>& intervals) {
16+
map<int, int> lookup;
17+
vector<int> result;
18+
for (int i = 0; i < intervals.size(); ++i) {
19+
lookup[intervals[i].start] = i;
20+
}
21+
for (const auto& interval : intervals) {
22+
const auto it = lookup.lower_bound(interval.end);
23+
if (it == lookup.end()) {
24+
result.emplace_back(-1);
25+
} else {
26+
result.emplace_back(it->second);
27+
}
28+
}
29+
return result;
30+
}
31+
};

0 commit comments

Comments
 (0)