【发布时间】:2016-12-19 01:42:31
【问题描述】:
我有以下向量:
std::vector<int> ExampleVector {10, 2, 5, 1, 8, 20};
我需要找到 3 个元素(A、B、C),其中:
1) A > B
2) (A + B) > C
3) A
在ExampleVector的情况下,10 5 8 满足上述条件。
我最初的尝试使用了多个具有给定条件的迭代器:
int main()
{
for(auto first_iterator = A.begin(); first_iterator != A.end(); first_iterator++)
{
for(auto second_iterator = first_iterator() + 1; second_iterator != A.end(); second_iterator++)
{
for(auto third_iterator = second_iterator() + 1; third_iterator != A.end(); third_iterator++)
{
bool condition_1 {(*first_iterator + *second_iterator) > *third_iterator};
bool condition_2 {(*second_iterator + *third_iterator) > *first_iterator};
if(condition_1 && condition_2)
{
return 1;
}
}
}
}
return 0;
}
这有效地导致:
iterator cycle1 cycle2 cycle3 cycle4 cycle5 cycle6 cycle7 ... N
first_iterator: 10 10 10 10 10 10 10
second_iterator: 2 2 2 2 5 5 5
third_iterator: 5 1 8 20 1 8 20
显然这是非常低效的!
我可以使用更好的方法来解决此类问题吗?
【问题讨论】:
-
你试过对向量进行排序吗?
标签: c++ loops vector time-complexity