LC Binary Search

# LC 704, 35, 34, 69 367

## LC 704 Binary Search

Binary Search, two std ways of implementations:

[## 704. 二分查找](https://programmercarl.com/0704.%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE.html#_704-%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE)

```python

# 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.搜索插入位置](https://programmercarl.com/0035.%E6%90%9C%E7%B4%A2%E6%8F%92%E5%85%A5%E4%BD%8D%E7%BD%AE.html#%E6%80%9D%E8%B7%AF)

## LC 34

[34. 在排序数组中查找元素的第一个和最后一个位置](https://programmercarl.com/0034.%E5%9C%A8%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84%E4%B8%AD%E6%9F%A5%E6%89%BE%E5%85%83%E7%B4%A0%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E5%92%8C%E6%9C%80%E5%90%8E%E4%B8%80%E4%B8%AA%E4%BD%8D%E7%BD%AE.html#%E6%80%9D%E8%B7%AF)

### 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](https://docs.python.org/3/library/bisect.html).

``` python

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)](https://leetcode.com/problems/sqrtx/)

### Logic

Analogue to the binary search.

`num[0-len(num)]`: `range(x)`

index 0: $0^2$

index -1: $x^2$, 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](https://leetcode.com/problems/valid-perfect-square/)

### Logic

Analogue to LC 367.

**Break condition:** `mid  *  mid  ==  num`


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值