题目:统计一个数字在排序数组中出现的次数。
就是简单的顺序查找。。。。那我还做麻烦了。。。。
# -*- coding:utf-8 -*-
class Solution:
def GetNumberOfK(self, data, k):
# write code here
if len(data) == 0:
return False
count = 0
for each in data:
if each == k:
count += 1
if count == 0:
return 0
else:
return count
直接用count函数。。。。
# -*- coding:utf-8 -*-
class Solution:
def GetNumberOfK(self, data, k):
# write code here
return data.count(k)
等下轮刷题要系统学一下排序算法:
2018.8.18
# -*- coding:utf-8 -*-
class Solution:
def GetNumberOfK(self, data, k):
# write code here
if len(data) == 0 or k not in data:
return 0
position = data.index(k)
count = 1
for i in range(position+1, len(data)):
if data[i] == k:
count += 1
return count