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. java和c通信相关的数据类型转换

    利用socket进行网络传输的时候往往需要将int转换为bytes,将string转换为bytes以及一些其他类型的数据转换 java和c类型的区别: 变量类型 C中字节数 Java中字节数 int ...

  2. mui 的多图片上传

    pickHead(){ var _this = this; plus.gallery.pick(function(path){ _this.headImage=path; var files = [{ ...

  3. Java数据结构——二叉树 增加、删除、查询

    //二叉树系统 public class BinarySystem { public static void main(String[] args) { BinaryDomain root = nul ...

  4. Python 学习笔记(七)Python字符串(四)

    输入输出 输入函数 raw_input (Python3:input) >>> raw_input("请输入一个字母") #获取输入内容的一个函数 请输入一个字母 ...

  5. javascript 六种基本数据类型转换

    javascript 六种基本数据类型转换 1.显式转换 通过手动进行类型转换,Javascript提供了以下转型函数: 转换为数值类型:Number(mix).parseInt(string,rad ...

  6. 3930: [CQOI2015]选数

    Time Limit: 10 Sec  Memory Limit: 512 MBSubmit: 1958  Solved: 979[Submit][Status][Discuss] Descripti ...

  7. 云监控自定义HTTP状态码说明

    您在使用站点监控时,返回的6XX状态码均为云监控自定义HTTP状态码,具体含义如下表所示: 状态码      含义     备注  610  HTTP连接超时      监测点探测您的网站时出现连接超 ...

  8. C调用约定__cdecl、__stdcall、__fastcall、__pascal分析

    参考原文地址:https://www.cnblogs.com/yenyuloong/p/9626658.html C/C++ 中不同的函数调用规则会生成不同的机器代码,产生不同的微观效果,接下来让我们 ...

  9. Xcode升到7.1插件失效解决方法

    Mac前段时间下载了新的OS系统与Xcode 7.1,然而在使用Xcode 7.1时,发现插件不能用了,瞬间木有爱了,正好交流群里有人问到了插件失效的问题,经过各路大神的神通最终用下面这种方法完美解决 ...

  10. TP3.2.3 接入阿里sms 短信接口

    阿里云短信接口 配置文件 config.php //阿里大鱼 'Ali_SMS' =>array( 'sms_temp' =>'短信模板', 'sms_sign' =>'签名', ' ...