You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否用C++标准库算法实现有序数组最长重复值序列查找?

功能说明

在有序数组(或vector)中查找最长的重复值序列,数组规模较大(最多可达百万条数据)。

说明

为避免初期优化建议:实际代码使用本人实现的有序区间增量上界替代std::upper_bound,此处为简化未使用该实现。

问题

能否借助单个或组合的C++标准库算法实现该功能,避免重复造轮子?比如简洁的一行式解决方案。
我不喜欢现有代码的两次遍历和繁琐的条件判断,但暂时找不到优化方向,仍希望能通过std算法或其组合简化实现。
请注意:提供代码仅为说明功能需求,无需过多关注;若建议优化方案,性能虽非核心但仍需考虑,请不要推荐使用map等动态结构收集大量数据的方案,仅需确认是否存在简洁的一行式解法。

代码

#include <algorithm>
#include <iostream>
#include <vector>

std::pair<std::vector<size_t>,size_t> get_longest_ranges(auto first, auto last)
{
    ptrdiff_t max_range = 0;
    size_t amount_of_ranges = 0;
    auto it = first;

    while (it != last) {
        auto it_end = std::upper_bound(it, last, *it);

        if (max_range == it_end - it) {
            ++amount_of_ranges;
        } else if (max_range < it_end - it) {
            max_range = it_end - it;
            amount_of_ranges = 1;
        }

        it = it_end;
    }

    std::vector<size_t> ranges;
    ranges.reserve(amount_of_ranges);

    it = first;
    while (it != last) {
        auto it_end = std::upper_bound(it, last, *it);

        if (it_end - it == max_range) {
            ranges.push_back(it-first);
        }

        it = it_end;
    }

    return { ranges,  max_range };
}

int main() {
    std::vector<int> v = { 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 7, 7, 7 };
    auto [starts, length] = get_longest_ranges(v.begin(),v.end());

    std::cout << "Max equal elements range length = " << length;

    for (auto start : starts) {
        std::cout << "\nAt position: " << start << " Values: ";
        for (size_t i = start; i < start + length; i++) {
            std::cout << v[i] << " ";
        }
    }
}

预期结果

Max equal elements range length = 4
At position: 3 Values: 2 2 2 2
At position: 15 Values: 7 7 7 7


内容的提问来源于stack exchange,提问作者Damir Tenishev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 18:57:22