剑指 Offer 53 - I. 在排序数组中查找数字 I

统计一个数字在排序数组中出现的次数。

示例1:

输入: nums = [5,7,7,8,8,10], target = 8
输出: 2

示例2:

输入: nums = [5,7,7,8,8,10], target = 6
输出: 0

思路1: 暴力解法,顺序遍历数组。
代码如下:

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        sum=0
        n=len(nums)
        for index in range(0,n):
            if nums[index] == target:
                sum = sum + 1
        return sum

思路2: 题目中出现 “有序”,用二分查找。

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        length = len(nums)
        low = 0
        high = length - 1
        count = 0
        
        if length == 0:
            return 0
        else: 
            while low <= high:
                mid =int((low + high)/2)
                if nums[mid] == target:
                    count = count +1
                    temp = mid +1
                    while temp < length and nums[temp] == target:
                        count = count +1
                        temp = temp + 1
                    temp = mid -1
                    while temp >=0 and nums[temp] == target:
                        count = count +1
                        temp = temp - 1
                    return count
                elif nums[mid] < target:
                    low = mid +1
                    high = high 
                else:
                    high = mid - 1
                    low = low
        if low > high:
            return 0            

注意:
1、边界问题
2、当nums[mid] == target时,要考虑其前后可能都会出现等于target的情况。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值