[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 ...
随机推荐
- 修改状态栏,电池,wifi的颜色为白色
修改状态栏,电池,wifi的颜色为白色 在info里面设置View controller-based status bar appearance,为no
- Sass 基础(七)
Sass Maps 的函数-map-remove($map,$key),keywords($args) map-remove($map,$key) map-remove($map,$key)函数是用来 ...
- Maximum Subsequence Sum
Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to ...
- Cent-OS——服务状态
查看MySQL状态: systemctl start mysqld #启用 systemctl stop mysqld #关闭 systemctl restart mysqld #重启MySQL服务 ...
- python 面向对象类与类之间的关系
主要内容: 1. 依赖关系 2. 关联关系, 组合关系, 聚合关系 3. 继承关系 4. 类中的特殊成员 引子 大千世界, 万物之间皆有规则和规律,我们的类和对象是对大千世界中的所有事物进行归类. 那 ...
- kali下添加用户和权限分配
1.添加用户 useradd -m test #-m的意思是创建用户的主目录 2.为用户test设置密码. passwd test 3.为添加的用户赋予权限(-a 添加 :-G 群组) 如果没有这一步 ...
- Asp.net 自定义CustomerSession 存放到Redis中
首先,引用 Redis 操作驱动组件:StackExchange.Redis.dll. 继承SessionStateStoreProviderBase 类, 实现方法: using System; u ...
- js判断是否为数字
function isNumber(value) { var patrn = /^(-)?\d+(\.\d+)?$/; if (patrn.exec(value) == null || value = ...
- php-语言参考-类型3.2-未完待续
一,PHP变量的8个类型 四种标量类型: boolean (布尔型) integer (整型) float (浮点型, 也称作 double) string (字符串) 两种复合类型: array ( ...
- ruby 操作csv
1.读取csv 文件中读取:一次读入全部(设置headers使 CSV#shift() 以CSV::Row对象返回而不是数组:使 CSV#read() 返回 CSV::Table 对象而不是数 ...