【MATLAB编程实例练习】-(32)最长连续数(Longest run of consecutive numbers)

该博客介绍了一道MATLAB编程题——找出数组中连续重复最多的数字。例如,给定数组a=[1 2 2 2 1 3 2 1 4 5 1],答案是2,因为它连续出现了三次。文中提供了代码实现及验证过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

来源于Mathwork上的Cody,Problem 672 - Longest run of consecutive numbers.

Given a vector a, find the number(s) that is/are repeated consecutively most often. For example, if you have
a = [1 2 2 2 1 3 2 1 4 5 1]
The answer would be 2, because it shows up three consecutive times.
If your vector is a row vector, your output should be a row vector. If your input is a column vector, your output should be a column vector. You can assume there are no Inf or NaN in the input. Super (albeit non-scored) bonus points if you get a solution that works with these, though.

代码

function val=longrun(a)
  A(1,1)=a(1);%第一列记录出现的元素
  A(1,2)=1;%第二列记录该元素连续出现的次数
  j=1;
for i=2:length(a)
    if a(i)==a(i-1)
        A(j,2)=A(j,2)+1;%连续出现,第二列+1
    else %新元素出现,对A的第j行初始化
        j=j+1;
        A(j,1)=a(i);
        A(j,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值