微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

计算数组中存在多少个“倒计时”序列

如何解决计算数组中存在多少个“倒计时”序列

我知道这听起来有点简单,但我正在尝试获取数组中存在的“倒计时”序列的计数。例子: [1,2,3,5,4,0] - > 2 ([3,2] 和 [5,3]) 我只需要一点点推动,拜托!

解决方法

每次倒计时中断时只需遍历列表即可增加计数器

Python,也称为伪代码:

def count_finder(l):
    prev = l[0]
    counter = 0
    inCount = False

    for num in l[1:]:
        if num == prev-1:    #Checks if the previous was 1 greater than this one
            inCount = True   #       if it is then "inCount" is True

        elif num+1 != prev and inCount:  #Checks if your exiting a countdown
            inCount = False              
            counter += 1   #Increment Counter
        prev = num         #Change previous number to current number for next loop
        
    if inCount: counter+=1  #If the loop ends while in a count down increment counter
    return counter
    
print(count_finder([9,8,7,6,5,4]))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。