如何将1D二进制序列绘制为2D图并提取1的最高峰值转十进制
实现方案
核心逻辑
- 先校验输入合法性,确保二进制序列长度和设定的2D矩阵容量匹配,且序列仅包含0和1
- 按行优先规则将1D二进制序列重塑为高度×宽度的2D矩阵
- 按列遍历矩阵,逐列统计无0中断的连续1长度,记录全局最大值即为所求峰值
完整代码
from typing import List def find_max_continuous_peak(height: int, width: int, binary_seq: List[int]) -> int: # 输入合法性校验 if len(binary_seq) != height * width: raise ValueError("二进制序列长度必须等于高度乘以宽度") if any(bit not in (0, 1) for bit in binary_seq): raise ValueError("二进制序列只能包含0和1") # 1D序列转2D矩阵(行优先填充) matrix = [binary_seq[i*width : (i+1)*width] for i in range(height)] max_peak = 0 # 按列遍历统计纵向连续1的最大长度 for col_idx in range(width): current_streak = 0 for row_idx in range(height): if matrix[row_idx][col_idx] == 1: current_streak += 1 max_peak = max(max_peak, current_streak) else: current_streak = 0 return max_peak # 示例验证 if __name__ == "__main__": test_height = 8 test_width = 10 # 构造测试序列,其中第三列存在5个连续的1,为全局最大值 test_binary = [0] * (test_height * test_width) for row in range(3, 8): test_binary[row * test_width + 2] = 1 print(find_max_continuous_peak(test_height, test_width, test_binary)) # 输出结果:5,与示例匹配
补充说明
如果需求是统计横向的连续峰值,仅需调整遍历顺序,先按行遍历再按列统计即可。当前实现默认统计高度方向的连续峰值,和题目示例要求一致。
内容的提问来源于stack exchange,提问作者yourickmovies
相关产品推荐
相关产品推荐

