美文网首页
Total Occurrence in Python(Binar

Total Occurrence in Python(Binar

作者: GakkiLove | 来源:发表于2018-03-29 20:52 被阅读0次

Given a target integer T and an integer array A sorted in ascending order, Find the total number of occurrences of T in A.

Examples:

A = {1, 2, 3, 4, 5}, T = 3, return 1
A = {1, 2, 2, 2, 3}, T = 2, return 3
A = {1, 2, 2, 2, 3}, T = 4, return 0

class Solution(object):
  def totalOccurrence(self, array, target):
    if len(array) == 0:
      return 0    
    low = 0
    high = len(array) - 1  
    while low < high - 1:
      mid = (low + high)/2
      if array[mid] < target:
        low = mid
      else: high = mid
        
    if array[low] == target:
      left = low
    elif array[high] == target:
      left = high
    else: 
      return 0
    
    start = 0
    end = len(array) - 1
    while start < end - 1:
      mid = (start + end)/2
      if array[mid] > target:
        end = mid
      else: start = mid
        
    if array[end] == target:
      right = end
    elif array[start] == target:
      right = start
    else: 
      return 0
    
    return right - left + 1

相关文章

网友评论

      本文标题:Total Occurrence in Python(Binar

      本文链接:https://www.haomeiwen.com/subject/bouvcftx.html