Title Description
Statistics the number of times a number appears in a sorted array.
Time limit: 1 second; Space limit: 32768K; Knowledge point: Array
Solving problems
Train of thought
Find the location index of the first identical number first, and then judge whether the number of consecutive numbers is identical from this position until different numbers appear and output the counting results.
# -*- coding:utf-8 -*- class Solution: def GetNumberOfK(self, data, k): # write code here if data==[]: #Consider all possible scenarios return 0 count = 0 # If so, find the first index of the same number for i in range(len(data)): if data[i]==k: break # Loop until the next number is different while data[i]==k: count += 1 i += 1 # If it's the last one, jump out of the loop if i == len(data): break return count
Train of thought two
Use dichotomy to find the first and last position of k.
# -*- coding:utf-8 -*- class Solution: def GetNumberOfK(self, data, k): # write code here # Binary search locates the first and last position of k lower = self.getLower(data,k) upper = self.getUpper(data,k) return upper-lower+1 # Get the subscript for the first occurrence of k def getLower(self, data, k): start = 0 end = len(data)-1 mid = (start + end) // 2 while start <= end: if data[mid] < k: #Pay attention to differences start = mid + 1 else: end = mid - 1 mid = (start + end) // 2 return start # Get the subscript for the last occurrence of k def getUpper(self, data, k): start = 0 end = len(data)-1 mid = (start + end) // 2 while start <= end: if data[mid] <= k: #Pay attention to differences start = mid + 1 else: end = mid - 1 mid = (start + end) // 2 return end