35. Search Insert Position

Description

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

Solution

二分法查找

 class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l, r = 0, len(nums) while l < r:
m = (l + r) // 2
if nums[m] == target:
return m
elif nums[m] > target:
r = m
else:
l = m + 1
return l

74. Search a 2D Matrix

Description

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

Example 1:

Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false

Solution

Approach 1: 二分查找

先按行二分确定目标所在行;再在该行中确定元素位置。

 class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]: return False
m, n = len(matrix), len(matrix[0]) if target < matrix[0][0] or target > matrix[m - 1][n - 1]:
return False start, end = 0, m
while start < end:
midrow = (start + end) // 2
if matrix[midrow][0] == target:
return True
elif target < matrix[midrow][0]:
end = midrow
else: start = midrow + 1
row = start - 1 l, r = 0, n while l < r:
midcol = (l + r) // 2
if matrix[row][midcol] == target: return True
elif matrix[row][midcol] < target:
l = midcol + 1
else: r = midcol
return False

Beats: 41.43%
Runtime: 48ms

Approach 2: 从右上到左下查找

若当前 > target, 则向前一列查找 => 则矩阵后几列均不用再考虑;
若当前 < target, 则向下一行查找 => 则矩阵前几行均不用再考虑。

 class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]: return False rows, cols = len(matrix), len(matrix[0])
row, col = 0, cols - 1
while True:
if row < rows and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] < target:
row += 1
else: col -= 1
else: return False

Beats: 41.67%
Runtime: 48ms

												

[Binary Search] Leetcode 35, 74的更多相关文章

  1. leetcode 704. Binary Search 、35. Search Insert Position 、278. First Bad Version

    704. Binary Search 1.使用start+1 < end,这样保证最后剩两个数 2.mid = start + (end - start)/2,这样避免接近max-int导致的溢 ...

  2. [LeetCode] questions conclusion_ Binary Search

    Binary Search T(n) = T(n/2) + O(1)   =>    T(n) = O(lg n) proof: 如果能用iterable , 就用while loop, 可以防 ...

  3. my understanding of (lower bound,upper bound) binary search, in C++, thanks to two post 分类: leetcode 2015-08-01 14:35 113人阅读 评论(0) 收藏

    If you understand the comments below, never will you make mistakes with binary search! thanks to A s ...

  4. 35. leetcode 501. Find Mode in Binary Search Tree

    501. Find Mode in Binary Search Tree Given a binary search tree (BST) with duplicates, find all the  ...

  5. [LeetCode] 35. Search Insert Position_Easy tag: Binary Search

    Given a sorted array and a target value, return the index if the target is found. If not, return the ...

  6. [LeetCode] 74. Search a 2D Matrix_Medium tag: Binary Search

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

  7. LeetCode 501. Find Mode in Binary Search Tree (找到二叉搜索树的众数)

    Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred ...

  8. [LeetCode] 35. Search Insert Position 搜索插入位置

    Given a sorted array and a target value, return the index if the target is found. If not, return the ...

  9. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

随机推荐

  1. 【luogu P3366 最小生成树】 模板

    这里是kruskal做法 当然prim也可以,至于prim和kruskal的比较: Prim在稠密图中比Kruskal优,Kruskal在稀疏图中比Prim优. #include<bits/st ...

  2. Mvc5 表单和HTML辅助方法

    ①表单的使用 在WebFrom里面你创建一个页面,页面上就会出<from></from>. 1,action和method属性 action表示目的,method表示表单传值方 ...

  3. JS JavaScript中的文档碎片 DocumentFragement JS性能优化

    文档碎片是什么: 如果我们要在一个ul中添加100个li,如果不使用文档碎片,那么我们就需要使用append经常100次的追加,这会导致浏览器一直不停的渲染,是非常消耗资源的.但是如果我们使用文档碎片 ...

  4. POJ 2007--Scrambled Polygon(计算凸包,点集顺序)

    Scrambled Polygon Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 10094   Accepted: 476 ...

  5. 2018 Wannafly summer camp Day2--Utawarerumono

    Utawarerumono 描述 题目描述: 算术是为数不多的会让久远感到棘手的事情.通常她会找哈克帮忙,但是哈克已经被她派去买东西了.于是她向你寻求帮助. 给出一个关于变量x,y的不定方程ax+by ...

  6. oracle 12.1的删除和创建公共用户问题

    版本12.1 ,cdb-rac模式 一个集群,4个节点,一个cdb,下面有12个pdb. os:linux 64 --- 删除用户 drop user c##test atler.log提示 ORA- ...

  7. vue js 保留小数

    toFixed(number,fractionDigits ){ //number 保留小数数 //fractionDigits 保留小数位数 var times = Math.pow(10, fra ...

  8. 企业Shell面试题及企业运维实战案例(三)

    1.企业Shell面试题1:批量生成随机字符文件名案例 使用for循环在/oldboy目录下批量创建10个html文件,其中每个文件需要包含10个随机小写字母加固定字符串oldboy,名称示例如下: ...

  9. django环境搭建和学习

    由于服务器down了好几天,前几天做的django的project全都在上面,无法继续开展工作,所以决定在本地重新部署一套virtualenv 之前没有好好整理过部署过程(其实也不难),所以决定写个随 ...

  10. 【ntp时间校准配置】

    Ntp(网络时间协议)是一种可以通过TCP/IP网络传播,其架构模式可分为C/S(客户端/服务器),PTP(对等),broatcast(广播), mutilbrocast(组播),无论在任何系统或设备 ...