次のような間隔を合計する必要があります。
1..6
2..4
The result is 1..6, so there are 6 numbers in the end.
別の例を次に示します。
4..6
8..10
14..16
4, 5, 6, 8, 9, 10, 14, 15, 16, the size is 9.
今、私はこれをO(N)でしなければなりません。STLを使用してすぐに思いついた、あまり良くないアプローチを次に示します。
#include <set>
#include <stdio.h>
using namespace std;
int main() {
int n;
scanf("%d", &n);
set<int> numbers;
int a, b;
for (int i = 0; i < n; i++) {
scanf("%d %d", &a, &b);
for (int u = a; u <= b; u++) {
numbers.insert(u);
}
}
printf("%d\n", numbers.size());
return 0;
}
O(N) でこれを行う方法について何か考えはありますか? 以前にソートする必要があることはわかっていますが、作成したばかりのこれを使用できます。
bool compare(const vector<int> first, const vector<int> second) {
if (first[0] == second[0]) return first[1] < second[1];
return first[0] < second[0];
}
sort(intervals.begin(), intervals.end(), compare);
つまり、O(log N + N) になります。
何か案は?ありがとうございました。