8 questions. Covers Quickselect.
Questions 1 to 5 of 8
Use the arrows to put the steps in order.
k
p
hi = p - 1
lo = p + 1
a[p]
lo
hi
cpp #include <algorithm> #include <iostream> #include <vector> struct Interval { int start; int end; }; std::vector<Interval> merge_intervals(std::vector<Interval> intervals) { std::vector<Interval> merged; if (intervals.empty()) { return merged; } std::sort(intervals.begin(), intervals.end(), [](const Interval& a, const Interval& b) { return a.start < b.start; }); merged.push_back(intervals[0]); for (std::size_t i = 1; i < intervals.size(); ++i) { Interval& last = merged.back(); if (intervals[i].start <= last.end) { last.end = std::max(last.end, intervals[i].end); } else { merged.push_back(intervals[i]); } } return merged; } void print(const std::vector<Interval>& list) { std::cout << "["; for (std::size_t i = 0; i < list.size(); ++i) { std::cout << (i ? ", " : "") << "[" << list[i].start << ", " << list[i].end << "]"; } std::cout << "]\n"; } int main() { print(merge_intervals({{2, 5}, {1, 2}, {6, 7}, {7, 9}})); }
free_time
cursor
merge_intervals
cpp #include <algorithm> #include <iostream> #include <vector> struct Interval { int start; int end; }; std::vector<Interval> merge_intervals(std::vector<Interval> intervals) { std::vector<Interval> merged; if (intervals.empty()) { return merged; } std::sort(intervals.begin(), intervals.end(), [](const Interval& a, const Interval& b) { return a.start < b.start; }); merged.push_back(intervals[0]); for (std::size_t i = 1; i < intervals.size(); ++i) { Interval& last = merged.back(); if (intervals[i].start <= last.end) { last.end = std::max(last.end, intervals[i].end); } else { merged.push_back(intervals[i]); } } return merged; } std::vector<Interval> free_time(const std::vector<Interval>& busy, int day_start, int day_end) { std::vector<Interval> gaps; int cursor = day_start; for (const Interval& b : merge_intervals(busy)) { if (b.start > cursor) { gaps.push_back({cursor, b.start}); } cursor = std::max(cursor, b.end); } if (cursor < day_end) { gaps.push_back({cursor, day_end}); } return gaps; } void print(const std::vector<Interval>& list) { std::cout << "["; for (std::size_t i = 0; i < list.size(); ++i) { std::cout << (i ? ", " : "") << "[" << list[i].start << ", " << list[i].end << "]"; } std::cout << "]\n"; } int main() { print(free_time({{10, 12}, {11, 13}}, 9, 15)); }
[1, 4]
[4, 5]
{{1, 4}, {4, 5}}
cpp merged.push_back(intervals[0]); for (std::size_t i = 1; i < intervals.size(); ++i) { Interval& last = merged.back(); if (intervals[i].start < last.end) { last.end = std::max(last.end, intervals[i].end); } else { merged.push_back(intervals[i]); } }
[[1, 5]]
<
[[1, 4], [4, 5]]
<=
[[1, 4]]
>=
[[4, 5]]
3 question(s) left on this page.