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

提示:

0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums 是一个非递减数组
-109 <= target <= 109

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

双指针 二分法

func search(nums []int, target int) int {
    i := 0
    j := len(nums) - 1

    for i <= j {
        mid := i + (j - i) / 2
        if nums[mid] <= target {
            i = mid + 1
        } else {
            j = mid - 1
        }
    }
    right := i

    i = 0
    for i <= j {
        mid := i + (j - i) / 2
        if nums[mid] < target {
            i= mid + 1
        } else {
            j = mid - 1
        }      
    }
    left := j
    return right - left - 1
}

 

优化后:二分边界转化为 target 与 target -1 的右边界的差

func search(nums []int, target int) int {
    return Bisection(nums, target) - Bisection(nums, target - 1)
}

func Bisection(nums []int, target int) int {
    i := 0
    j := len(nums) - 1
    for i <= j {
        mid := i + (j - i) / 2
        if nums[mid] <= target {
            i = mid + 1
        } else {
            j = mid - 1
        }
    }
    return i
}

 

posted @ 2023-04-10 15:26  slowlydance2me  阅读(8)  评论(0编辑  收藏  举报