[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 ...
随机推荐
- 时空隧道FQ
给你推荐一款海外网站加速工具,为科技工作者.海外归国人员.企业团队.外贸工作者提供海外上网服务,永久免费. 国外网址:https://chrome.google.com/webstore/detail ...
- 外部的 JavaScript
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content=&q ...
- Xcode DeviceSupport
问题:Could not locate device support files. This iPhone 6s is running iOS 12.1 (16B5059d), which may n ...
- @font-face css3自定义个性化字体
使用第三方平台转换字体文件为font-face所支持的格式. TureTpe(.ttf)格式 支持浏览器:IE9+,Firefox3.5+,Chrome4+,Safari3+,Opera10+,iOS ...
- JavaScript 基础(五) 函数 变量和作用域
函数定义和调用 定义函数,在JavaScript中,定义函数的方式如下: function abs(x){ if(x >=0){ return x; }else{ return -x; } } ...
- Eclipse工具查看依赖的JDK、Maven源码方法
一.Eclipse软件里查看JDK依赖源码 1.Window->Preferences->Java->Installed JREs 2.如图: 二.Eclipse软件里查看Maven ...
- vue服务端渲染添加缓存
缓存 虽然 Vue 的服务器端渲染(SSR)相当快速,但是由于创建组件实例和虚拟 DOM 节点的开销,无法与纯基于字符串拼接(pure string-based)的模板的性能相当.在 SSR 性能至关 ...
- C#中给WebClient添加代理Proxy
效果图: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; ...
- PHP计算两个时间戳之间间隔时分秒
/功能:计算两个时间戳之间相差的日时分秒//$begin_time 开始时间戳//$end_time 结束时间戳function timediff($begin_time,$end_time){ if ...
- Laravel -- 模型
模型文件 <?php namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model { / ...