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. mui 的多图片上传

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

  2. 菜鸟崛起 Ajax

    AJAX概述 1 什么是AJAX AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”.即使用Javascript语言与服务器进 ...

  3. c# LRU实现的缓存类

    在网上找到网友中的方法,将其修改整理后,实现了缓存量控制以及时间控制,如果开启缓存时间控制,会降低效率. 定义枚举,移除时使用 public enum RemoveType    {        [ ...

  4. MySQL备份恢复之Xtrabackup

    Preface       Today,I'm gonna use the Xtrabackup tool to demonstrate the procedure of backing up MyS ...

  5. pycharm中配置pyspark

    1 下载官网spark-2.1.1-bin-hadoop2.7.tgz(版本自己选择),解压将文件放在了指定路径下,这个文件夹里面有python文件,python文件下还有两个压缩包py4j-some ...

  6. 【php学习-5】

    mutil_query($result)){ //多查询 where } //执行查询 /* $result=$cone->query("SELECT * from test" ...

  7. nodejs--http

    http模块主要用到四个方法: 1.Server类 const http = require('http'); let server = new Server(); server.on('reques ...

  8. mongodb的高级查询

    db的帮助文档 输入:db.help(); db.AddUser(username,password[, readOnly=false])  添加用户 db.auth(usrename,passwor ...

  9. JavaSE 第二次学习随笔(关于内存的小题)

    class HelloA { public HelloA() { System.out.println("HelloA"); } { System.out.println(&quo ...

  10. python入门(续)

    类和方法 创建类 class A(object): def add(self, a,b ): return a+b count = A() print(count.add(3,5)) 初始化工作 cl ...