题解 | #数字在升序数组中出现的次数#
数字在升序数组中出现的次数
https://www.nowcoder.com/practice/70610bf967994b22bb1c26f9ae901fa2
import re # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param nums int整型一维数组 # @param k int整型 # @return int整型 # class Solution: def GetNumberOfK(self , nums: List[int], k: int) -> int: # write code here len_num = len(nums) if len_num == 0: return 0 left = 0 right = len_num - 1 while(left < right): mid = (left+right)//2 if(nums[mid]>=k): right = mid else: left = mid+1 # 存在两种例外情况,1:left>len_num-1 2: 找到的中间值不等于k if left>=len_num or nums[left]!=k: return 0 # 存一下左边界 pos_left = left # 找右边界,因为要logn 复杂度 # 重置一下条件 left = 0 right = len_num - 1 while(left<right): mid = (left+right+1)//2 if(nums[mid]<=k): left = mid else: right = mid-1 pos_right = left return pos_right - pos_left+1
剑指offer刷题笔记 文章被收录于专栏
24秋招剑指offer刷题的笔记