なぜ使用std::set_difference
:方法についてそれでは、
OK:このランタイムは大まかにうまくいくv1.size() == n
とv2.size() == m
場合
std::vector<int> test(
std::vector<int> v1,
std::vector<int>& v2)
{
// The algorithm we use requires the ranges to be sorted:
std::sort (v1.begin(), v1.end());
std::sort (v2.begin(), v2.end());
// our output vector: reserve space to avoid copying:
std::vector<int> v3;
v3.reserve (v2.size());
// Use std::set_difference to copy the elements from
// v2 that are not in v1 into v3:
std::set_difference (
v2.begin(), v2.end(),
v1.begin(), v1.end(),
std::back_inserter(v3));
return v3;
}
this:
void test2(
std::vector<int> v1,
std::vector<int> v2)
{
// We can still sort this without affecting the indices
// in v2:
std::sort (v1.begin(), v1.end());
// Replace all the elements in v1 which appear in v2
// with -1:
std::replace_if (v2.begin(), v2.end(),
[&v1] (int v)
{
return std::binary_search(v1.begin(), v1.end(), v);
}, -1);
}
リニアではありません。複雑さを見積もることは、OPの練習として残されています。
第3の選択肢はこれです:配列がソートされている場合は
void test3(
std::vector<int> v1,
std::vector<int>& v2)
{
// We can still sort this without affecting the indices
// in v2:
std::sort (v1.begin(), v1.end());
auto ret = std::stable_partition (
v2.begin(), v2.end(),
[&v1] (int v)
{
return !std::binary_search(v1.begin(), v1.end(), v);
});
v2.erase (ret, v2.end());
}
再び、直線的ではないが、オプション...
、 'のstd :: set_difference'があると思われますあなたが欲しいもの。 – Jarod42
現在のプレゼンテーションで 'O(n)'を得る方法はありません。 –
ありがとう@GillBates。あなたはこの操作のためにO(n)を得る方法の提案がありますか? –