题目描述

统计一个数字在升序数组中出现的次数。

  1. # -*- coding:utf-8 -*-
  2. class Solution:
  3. def GetNumberOfK(self, data, k):
  4. # write code here
  5. def get_first(data,k):
  6. l,r = 0,len(data)
  7. while l<r:
  8. m = (l+r)/2
  9. if data[m]>=k:
  10. r = m
  11. else:
  12. l = m + 1
  13. return l
  14. first_index = get_first(data, k)
  15. last_index = get_first(data, k + 1)
  16. if first_index == len(data) or data[first_index]!=k:
  17. return 0
  18. else:
  19. return last_index-first_index