算法题/数字在排序数组中出现的次数

来源:互联网 发布:php 获取1688商品 编辑:程序博客网 时间:2024/05/22 03:36

python2.7

例如输入排序数组{ 1, 2, 3, 3, 3, 3, 4, 5}和数字 3 ,由于 3 在这个数组中出现了 4 次,因此输出 4 。

#coding:utf-8#方法一def count_num(a,k):    if len(a) == 0:        return 0    else:        return a.count(k)#方法二def count_num1(a,k):    count = 0    first_index = a.index(k)    i = first_index    while i < len(a) and a[i] == k:        count += 1        i += 1    return countprint(count_num([1,2,2,2,2,2,2,3,4,5],2)) print(count_num1([1,2,2,2,2,2,2,3,4,5],2)) 

这里写图片描述