Dre*_*ann 12
您正在寻找的标准算法是std :: adjacent_find.
这是一个解决方案,它也使用lambda来使谓词干净:
int first_gap( std::vector<int> vec )
{
// Handle the special case of an empty vector. Return 1.
if( vec.empty() )
return 1;
// Sort the vector
std::sort( vec.begin(), vec.end() );
// Find the first adjacent pair that differ by more than 1.
auto i = std::adjacent_find( vec.begin(), vec.end(), [](int l, int r){return l+1<r;} );
// Handle the special case of no gaps. Return the last value + 1.
if ( i == vec.end() )
--i;
return 1 + *i;
}
Run Code Online (Sandbox Code Playgroud)
jmu*_*llo 10
选中的答案使用<进行比较.!=更简单:
int find_gap(std::vector<int> vec) {
std::sort(vec.begin(), vec.end());
int next = 1;
for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
if (*it != next) return next;
++next;
}
return next;
}
find_gap(1,2,4,5) = 3
find_gap(2) = 1
find_gap(1,2,3) = 4
Run Code Online (Sandbox Code Playgroud)
我没有传递对向量的引用,因为a)他说时间无关紧要b)所以我不改变原始向量的顺序.
对列表进行排序然后进行线性搜索似乎是最简单的解决方案。根据列表的预期组成,您可以使用不太通用的排序算法,如果您自己实现排序,则可以在排序期间跟踪数据,这些数据可用于加速(或完全消除)搜索步骤。我认为这个问题没有任何特别优雅的解决方案
归档时间: |
|
查看次数: |
4681 次 |
最近记录: |