
如何快速统计出一亿行由0和1组成的数字里面的1连续出现几次及标记后出现的次数?请提供具体思路及代码。

关注你需要统计一亿行由 0 和 1 组成的数字中,连续出现的 1 的次数,并且标记每次连续 1 出现后紧接着的数字是 0 的次数。也就是说,我们要找出连续的 1 的“段”以及这些段后跟随的 0 的个数。
这是一个典型的大数据处理任务。由于数据量巨大,我们的目标是设计一个 高效的算法,尽量减少内存消耗并提升计算速度。考虑到你可能在使用 C++ 和 Python,下面我会分别给出两种语言的实现思路及代码。
mmap)来处理大文件。#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
// 统计连续 1 的段数及每段后跟随的 0 的次数
void count_consecutive_ones_and_zeros(const string& filename) {
ifstream file(filename);
string line;
int total_one_segments = 0; // 连续 1 的段数
int total_zero_after_ones = 0; // 每段 1 后跟的 0 的次数
while (getline(file, line)) {
int consecutive_ones = 0;
bool in_one_segment = false;
for (size_t i = 0; i < line.size(); ++i) {
if (line[i] == '1') {
if (!in_one_segment) {
in_one_segment = true;
total_one_segments++; // 开始一个新的连续 1 的段
}
consecutive_ones++;
} else {
if (in_one_segment) {
// 结束连续 1 的段,记录后面的 0
if (i + 1 < line.size() && line[i + 1] == '0') {
total_zero_after_ones++;
}
}
in_one_segment = false;
consecutive_ones = 0;
}
}
}
cout << "Total segments of consecutive 1s: " << total_one_segments << endl;
cout << "Total zeros following 1s: " << total_zero_after_ones << endl;
}
int main() {
string filename = "big_data.txt"; // 输入文件名
count_consecutive_ones_and_zeros(filename);
return 0;
}
in_one_segment 来标记是否当前正在遍历连续的 1。total_one_segments 计数器。total_zero_after_ones 计数器。mmap):对于极大文件,可以使用内存映射(mmap)来高效读取文件,不需要将整个文件加载到内存。Python 可以利用 流式处理 来避免一次性将数据全部加载到内存。我们将逐行读取数字,使用类似的状态机方法来统计连续的 1 和后跟的 0 的次数。
def count_consecutive_ones_and_zeros(filename):
total_one_segments = 0 # 连续 1 的段数
total_zero_after_ones = 0 # 每段 1 后跟随的 0 的次数
with open(filename, 'r') as file:
for line in file:
line = line.strip() # 去掉行尾换行符
in_one_segment = False
for i in range(len(line)):
if line[i] == '1':
if not in_one_segment:
in_one_segment = True
total_one_segments += 1 # 新的连续 1 段
else:
if in_one_segment and i + 1 < len(line) and line[i + 1] == '0':
total_zero_after_ones += 1 # 连续 1 后面跟 0
in_one_segment = False
print(f"Total segments of consecutive 1s: {total_one_segments}")
print(f"Total zeros following 1s: {total_zero_after_ones}")
if __name__ == "__main__":
filename = "big_data.txt" # 输入文件名
count_consecutive_ones_and_zeros(filename)
open(filename) 逐行读取文件,避免将整个数据加载到内存。in_one_segment 来标记是否当前在一个连续 1 的段中。total_one_segments。total_zero_after_ones。对于非常大的数据集,可以使用内存映射方式来高效读取数据,避免每次读取都消耗大量的时间。在 C++ 中,使用 mmap,在 Python 中,可以使用 mmap 模块。
std::thread,在 Python 中,可以使用 concurrent.futures.ThreadPoolExecutor。readlines 或按块读取),避免每次读取一行。通过流式读取和状态机方法,我们能够高效地统计一亿行由 0 和 1 组成的数字中连续出现的 1 的段数以及每段后跟的 0 的次数。这种方法避免了内存的浪费,适用于大规模数据的处理。同时,适当的优化(如多线程、内存映射)可以进一步提升计算性能。