Number of times a number appears in a sorted array

Problem Description
Count the number of times a number appears in a sorted array.
Problem- solving idea 1:
Because it is an order, use binary search to find the first bit larger than k and then traverse it in turn.

class Solution:
    def GetNumberOfK(self, data, k):
        # write code here
        if not data or data[-1] < k or data[0] > k: #判断k是否可能在data中,不在则返回0
            return 0
        cum = 0
        #寻找的是第一大于k的索引
        #从0到最后一位的索引加1,这样当最后一位就是k的时候,索引也依旧比这一位大于1,所以不用单独考虑
        i, j = 0, len(data) 
        #返回第一个大于k的数。
        while i < j:
            mid = (i + j) // 2
            if data[mid] > k:
                j = mid
            else:
                i = mid + 1
        #因为返回的是第一个比k大的索引,所以要减1
        while data[j-1] == k and j-1>=0:
            cum+=1
            j-=1
        return cum

Solution 2:
Find the index of the first k and the last k, then subtract and add 1.

class Solution:
    def GetNumberOfK(self, data, k):
        # write code here
        if not data or data[-1] < k or data[0] > k: #判断k是否可能在data中,不在则返回0
            return 0
        def get_right(data,k):

            start,end = 0, len(data) -1
            while start <= end:
                mid = (start + end) // 2
                if data[mid] > k:
                    end = mid - 1
                else:
                    res = mid
                    start = mid + 1
            return  res
        def get_left(data,k):
            start,end = 0, len(data) -1
            while start <= end:
                mid = (start + end) // 2
                if data[mid] < k:
                    start = mid + 1
                else:
                    res = mid
                    end = mid - 1
            return  res
        return get_right(data,k) - get_left(data,k) + 1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324415216&siteId=291194637