LC 704, 35, 34, 69 367 / LC Binary Search

LC 704, 35, 34, 69 367

LC 704 Binary Search

Binary Search, two std ways of implementations:
## 704. 二分查找

# lc 704
def search(self, nums: List[int], target: int) -> int:
    low = 0
    high = len(nums)
    while low < high:
        mid = low + (high - low) // 2
        if nums[mid] < target:
            low = mid + 1
        elif nums[mid] > target:
            high = mid
        else:
            return mid
    return -1

Logic

  • In this case, the initial condition is set to [low, high).
  • high: strict upper bound, which gives low < high.
  • When updating, [low, high) condition hold.

LC 35

35.搜索插入位置

LC 34

34. 在排序数组中查找元素的第一个和最后一个位置

Logic:

  • Two binary search, one for the lower bound, another for the upper bound.
  • edge cases:
    • len(nums) == 0
    • if the first binary search results in the case where the target is not within the range of the nums[], there is no need for the second binary search.
Using bisect

It serves more like a wrapper. Reference here.

import bisect
def searchRange2(self, nums: List[int], target: int) -> List[int]:
    start = bisect.bisect_left(nums, target)
    if start == len(nums) or nums[start] != target:
        return [-1, -1]
    return [start, bisect.bisect_right(nums, target, lo=start) - 1]

LC 69

69. Sqrt(x)

Logic

Analogue to the binary search.
num[0-len(num)]: range(x)
index 0: 0 2 0^2 02
index -1: x 2 x^2 x2, yeah I know there is a better bound by doing some math, but no thanks.
Break condition: target == nums[mid]: mid * mid <= x < (mid + 1) * (mid + 1)

LC 367

367. Valid Perfect Square

Logic

Analogue to LC 367.
Break condition: mid * mid == num

  • 16
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值