向量中连续数的计数

时间:2015-09-29 06:37:16

标签: c++ vector

假设我有以下排序的向量作为输入:

[22]
[22, 23]
[22, 46]
[22, 46, 47]
[22,23,33,44,45,46,55,56]

我想要以下输出显示每个向量中连续数字的计数:

1 //edgecase: if there's 1 number it's consecutive)
2 //22, 23 are 2 consecutive numbers
0 //22, 46 not consecutive
2 //46, 47 are 2 consecutive numbers
7 //22,23 (2) 44,45,46 (3) 55,56(2) 7 consecutive numbers

我的矢量不会有重复。

到目前为止我所拥有的是:

vector<int> numbers;
int consecCount=0;
if (numbers.size()==1)
        consecCount++;
else{
    for (size_t k=1; k<numbers.size(); k++) {
        if (numbers[k]==numbers[k-1]+1) {
            consecCount +=2;
        }
}

当然这种方法对最后一个数组不起作用。解决方案似乎非常错误。

我的实际向量非常大,所以更喜欢任何不涉及使用另一个向量的想法

3 个答案:

答案 0 :(得分:2)

这样的东西?

size_t conseccount(const vector<int> &v)
{
    size_t s = v.size();
    size_t ret = 0;
    bool seqstart = true;
    if(s < 2) return 0;
    for(size_t i = 1; i < s; i++)
    {
        if(v[i - 1] + 1 == v[i])
        {
            if(seqstart) ret++;
            seqstart = false;
            ret++;
        }
        else seqstart = true;
    }
    return ret;
}

答案 1 :(得分:2)

预期输出

vector    question  why      my query
1         1         22       Is it 1 or 0.  // I don't understand why 
2         2         22,23   
3         0              
4         2        46,47 
5         7       22,23 44,45,46  55,56

即计算作为序列一部分的条目数,使得a [i] = a [i + 1]

关键是要确保你单独计算,但在序列的末尾添加一个。

您需要检查您是否处于序列bool bInSequence,最初是false。转换为序列时,将其设置为true

然后当你离开序列或循环时,你要添加一个。

vector<int> numbers;
int consecCount=0;
if (numbers.size()==1)
   consecCount++;
else{
    bool inSequence = false;
    for (size_t k=1; k<numbers.size(); k++) {
        if (numbers[k]==numbers[k-1]+1) {
            consecCount +=1;
            inSequence = true;
        } else if ( inSequence ) {
            inSequence = false;
            consecCount ++;
        }
    }
    if( inSequence == true ) {
        // inSequence = false; //not needed, but logically correct
        consecCount ++;
    }
}

答案 2 :(得分:1)

使用std::adjacent_find,您可以执行以下操作:

std::size_t count_consecutive_sequence(const std::vector<int> &v)
{
    if (v.size() <= 1) {
        return v.size();
    }

    std::size_t res = 0;
    for (auto it = v.begin(); it != v.end(); ) {
        auto e = std::adjacent_find(it, v.end(),
                                    [](int lhs, int rhs) { return lhs + 1 != rhs; });

        if (it == e || it + 1 == v.end()) {
            ++it;
        } else {
            if (e != v.end()) {
                ++e;
            }
            res += distance(it, e);
            it = e;
        }
    }
    return res;
}

Demo