python--剑指offer--简单--53 - I. 在排序数组中查找数字 I-爱代码爱编程
from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums:
return 0
l, r = 0, len(nums)-1
while l <= r:
mid = (l + r) // 2
if nums[mid] > target:
r = mid - 1
elif nums[mid] < target:
l = mid + 1
else:
break
if l > r:
return 0
count = 1
x = mid - 1
while x >= 0 and nums[x] == target:
count += 1
x -= 1
x = mid + 1
r = len(nums) - 1
while x <= r and nums[x] == target:
count += 1
x += 1
return count
if __name__ == '__main__':
solution = Solution()
nums = [5, 7, 7, 8, 8, 10]
target = 8
# nums = [5, 7, 7, 8, 8, 10]
# target = 6
res = solution.search(nums, target)
print(res)
[题目源于leetcode]
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接: https://blog.csdn.net/Chasing__Dreams/article/details/109398489