[Binary Search] Leetcode 35, 74
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的更多相关文章
- 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导致的溢 ...
- [LeetCode] questions conclusion_ Binary Search
Binary Search T(n) = T(n/2) + O(1) => T(n) = O(lg n) proof: 如果能用iterable , 就用while loop, 可以防 ...
- 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 ...
- 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 ...
- [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 ...
- [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 ...
- 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 ...
- [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 ...
- Leetcode 笔记 99 - Recover Binary Search Tree
题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...
随机推荐
- Android学习笔记_55_Tween动画 (渐变、缩放、位移、旋转)
Android 平台提供了两类动画. 一类是Tween动画,就是对场景里的对象不断的进行图像变化来产生动画效果(旋转.平移.放缩和渐变).第二类就是 Frame动画,即顺序的播放事先做好的图像,与gi ...
- ContentProvider 、 ContentResolver 、 ContentObserver
说说ContentProvider . ContentResolver . ContentObserver 之间的关系**a. ContentProvider 内容提供者,用于对外提供数据 b. Co ...
- 如何使用Xcode的Targets来管理开发和生产版本的构建
如何使用Xcode的Targets来管理开发和生产版本的构建 想象一下,你已经完成了应用程序的开发和测试,现在准备提交正式版本.问题是,一些web服务的url指向了测试服务器,同时API密钥被配置用于 ...
- Lucene作为一个全文检索引擎
Lucene作为一个全文检索引擎,其具有如下突出的优点: (1)索引文件格式独立于应用平台.Lucene定义了一套以8位字节为基础的索引文件格式,使得兼容系统或者不同平台的应用能够共享建立的索引文件. ...
- [SCOI2009]windy数(数位DP)
题目描述 windy定义了一种windy数.不含前导零且相邻两个数字之差至少为2的正整数被称为windy数. windy想知道, 在A和B之间,包括A和B,总共有多少个windy数? 输入输出格式 输 ...
- c++:请编写一个函数,对字符串“zheshigekendiedetimu”按从大到小的顺序排列,并截取后n位数(n为函数的一个参数)。
String str="zheshigekendiedetimu"; StringBuffer buff=new StringBuffer(str); char[] arr=str ...
- chrome浏览器中 F12 功能的简单介绍
chrome浏览器中 F12 功能的简单介绍 由于F12是前端开发人员的利器,所以我自己也在不断摸索中,查看一些博客和资料后,自己总结了一下来帮助自己理解和记忆,也希望能帮到有需要的小伙伴,嘿嘿! 首 ...
- ArrayList调用remove(int index)抛出UnsupportedOperationException问题分析以及解决记录
使用Arrays转数组成为List后,不能调用add(...)和remove(...)方法,此时如果调用就会抛出UnsupportedOperationException异常 原因 其实Arrays. ...
- 路由器基础配置之ospf基础配置
我们将以上面的拓扑图进行本次ospf的实验,目的是能当三台pc机互通 先配置好pc机的IP地址,注意一定要给pc机设置好网关,接下来配置路由器的IP地址 router4 enable 进入特权模式 c ...
- checkbox的第三种状态--不确定状态
视觉上,checkbox有三种状态:checked.unchecked.indeterminate(不确定的).看起来就像这样子: