【算法训练】剑指offer#53 - I 在排序数组中查找数字 I

一、描述

剑指 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

二、思路

  • 从头遍历数组然后比较,看看超时么
def search(self, nums: List[int], target: int) -> int:
        result = 0
        for i in nums:
            if i == target:
                result += 1
        return result

通过了,再试试其他方法

  • 折半不行吧,如果不是首尾有target的话,没有结束标志,只对范围大的数组折半感觉有点取巧
  • 还是得折半。。。
  • 害,以后再写折半

三、解题

def search(self, nums: List[int], target: int) -> int:
        result = 0
        for i in nums:
            if i == target:
                result += 1
        return result
posted @ 2022-01-18 19:31  小拳头呀  阅读(28)  评论(0编辑  收藏  举报