劍指offer——陣列在排序陣列中出現的次數
阿新 • • 發佈:2018-12-14
記錄次數,直接用data.count(k)也通過了。或者常規演算法,出現有序用二分查詢。
class Solution: def GetNumberOfK(self, data, k): # write code here if len(data)==0: return 0 count=0 low=0 high=len(data)-1 while low<high: mid=(low+high)//2 if data[mid]==k: count+=1 elif data[mid]<k: low=mid+1 else: high=mid-1 return count
直接用常規的二分查詢,執行超時,需要進一步改進。因為有序所以查詢到的k如果數值相同,肯定在周圍,而上法必將複雜。所以我們只用二分查詢定位其位置而不直接統計次數,位置確定後再通過左右數值判斷次數。
class Soluton: def BinarySearch(self,data,mlen,k): low=0 high=mlen-1 while low<high: mid=(low+high)//2 if data[mid]==k: return mid elif data[mid]<k: low=mid+1 else: high=mid-1 return -1 def GetNumberOfK(self,data,k): mlen=len(data) index=self.BinarySearch(data,mlen,k) if index==-1: return 0 count=1 for i in range(1,mlen): if index+i<mlen and data[index+i]==k: count+=1 if index-i>=0 and data[index-i]==k: count+=1 return count