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. 【题解】洛谷P1350 车的放置(矩阵公式推导)

    洛谷P1350:https://www.luogu.org/problemnew/show/P1350 思路 把矩阵分为上下两块N与M 放在N中的有i辆车 则放在M中有k-i辆车 N的长为a   宽为 ...

  2. CodeForces - 348A Mafia (巧妙二分)

    传送门: http://codeforces.com/problemset/problem/348/A A. Mafia time limit per test 2 seconds memory li ...

  3. Unity3d-制作粒子光环特效

    http://blog.csdn.net/ozhangseno/article/details/70799611

  4. 自动化测试selenium教程

    什么是自动化测试: 自动帮我们测试一个系统里面的主要功能,一个app.电脑网站.网页,每个系里面许多的功能,好比一个淘宝页面,里面N多功能,登录.注册,推荐,商品详情.评论等等:软件生命周期:需求调研 ...

  5. Oracle 用户、授权、角色管理

    Oracle 用户管理 一.创建用户的Profile文件SQL> create profile student limit // student为资源文件名FAILED_LOGIN_ATTEMP ...

  6. the “inner class” idiom

    有些时候我们需要upcast为多种类型,这种情况下除了可以使用multiply inherits还可以inner class. 以下为例子: //: C10:InnerClassIdiom.cpp / ...

  7. Windows无法安装到这个磁盘 选中的磁盘具有MBR分区表解决方法

    在安装 win10的时候,会出现这种提示:Windows 无法安装到这个磁盘.选中的磁 盘具有 MBR 分区表.在 EFI 系统上, Windows 只能安装到 GPT 磁盘.出现这种 情况主要是因为 ...

  8. 数组reduce方法以及高级技巧

    基本概念: reduce()方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终为一个值. reduce为数组中的每一个元素依次执行回调函数.不包括数组中被删除或从未赋值的元素,接受两 ...

  9. vector基础操作

    //vector< T> vec; //构造一个名为vec的储存数据类型为T的动态数组.其中T为需要储存的数据类型 //初始时vec为空 //push_back 末尾添加一个元素 //po ...

  10. PP: 混合生产方式(MTO与MTS为例)(转)

    http://blog.sina.com.cn/s/blog_4c01b7650100yf1d.html PP: 混合生产方式(MTO与MTS为例) 一.业务概览某公司生产的同一种产品正常情况下客户无 ...