题目:

搜索二维矩阵

写出一个高效的算法来搜索 m × n矩阵中的值。

这个矩阵具有以下特性:

  • 每行中的整数从左到右是排序的。
  • 每行的第一个数大于上一行的最后一个整数。
样例

考虑下列矩阵:

[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]

给出 target = 3,返回 true

挑战

O(log(n) + log(m)) 时间复杂度

解题:

更新730

直接二分查找

    public boolean searchMatrix(int[][] A, int target) {
// write your code here
if(A == null || A.length == 0 || A[0].length ==0)
return false;
int row = A.length;
int col = A[0].length;
int len = row * col;
int left = 0;
int right = len-1 ;//
while(left <= right){
int mid = left + (right - left)/2;
int x = A[mid/col][mid%col];
if(x==target){
return true;
}else if(x>target){
right = mid-1;
}else{
left = mid+1;
}
}
return false;
}

1.最简单的方法就是遍历整个矩阵,时间复杂度:O(log(mn)),这个应该等于O(long(n)+log(m))

2.题目给的矩阵是有序矩阵,先按照最后一列二分查找,确定列,再二分确定行,时间复杂度O(log(m)) + O(log(n)),哦,哦,哦,题目的挑战可能是搞错了。。。

1.暴力

Java程序:

public class Solution {
/**
* @param matrix, a list of lists of integers
* @param target, an integer
* @return a boolean, indicate whether matrix contains target
*/
public boolean searchMatrix(int[][] matrix, int target) {
// write your code here 二分查找
if(matrix==null)
return false;
int m = matrix.length;
if(m==0)
return false;
int n = matrix[0].length;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++)
if(matrix[i][j]==target)
return true;
}
return false;
}
}

总耗时: 1571 ms

Python程序:

class Solution:
"""
@param matrix, a list of lists of integers
@param target, an integer
@return a boolean, indicate whether matrix contains target
"""
def searchMatrix(self, matrix, target):
# write your code here
if matrix==None:
return False
m = len(matrix)
if m==0:
return False
n = len(matrix[0])
for i in range(m):
for j in range(n):
if matrix[i][j]==target:
return True
return False

总耗时: 260 ms

2.二分法

利用二分思想程序,先求所在的行,再求所在的列,搞了好久,边界错了好多次。。。

Java程序:

public class Solution {
/**
* @param matrix, a list of lists of integers
* @param target, an integer
* @return a boolean, indicate whether matrix contains target
*/
public boolean searchMatrix(int[][] matrix, int target) {
// write your code here 二分查找
if(matrix==null)
return false;
int nrow = matrix.length;
if(nrow==0)
return false;
int ncol = matrix[0].length;
// 行 nrow
//列 ncol
int row = rowbinSearch(matrix,0,nrow-1,ncol,target);
int col = colbinSearch(matrix,0,ncol-1,row,target);
if(col!=-1)
return true;
return false;
}
// 找出所在的行
private int rowbinSearch(int[][] matrix,int left,int right,int ncol,int target){
//矩阵matrix ,二分的两个界:left、right,矩阵的最后一列ncol,目标值target
int median = (left + right)/2;
int row = median;
if(left==right)
return left;
if(matrix[left][ncol-1]<=target && matrix[left+1][ncol-1]>target)
return left;
if(matrix[median][ncol-1]>= target && matrix[median][0]<=target)
return median;
if(matrix[median][ncol-1]<target)
row = rowbinSearch(matrix,median+1,right,ncol,target);
else
row = rowbinSearch(matrix,left,median-1,ncol,target);
return row;
}
// 找出所在的列
private int colbinSearch(int[][] matrix,int left,int right,int row,int target){
//矩阵matrix ,二分的两个界:left、right,target所在的行: row,目标值target
int median = (left + right)/2;
int col = median;
if(left>right)
return -1;
if(left==right && matrix[row][left]!=target)
return -1;
if(matrix[row][median]==target)
return median;
if(matrix[row][median]<target)
col = colbinSearch(matrix,median+1,right,row,target);
else
col = colbinSearch(matrix,left,median-1,row,target);
return col;
}
}

总耗时: 2246 ms

3.暴力2.0

九章算法中看到的,给的Java程序利用二分法,但是没有用递归,给的Python程序,没有明显的用到矩阵变量,但是通过商和余数确定所在的行和列

Python程序:

class Solution:
"""
@param matrix, a list of lists of integers
@param target, an integer
@return a boolean, indicate whether matrix contains target
"""
def searchMatrix(self, matrix, target):
# write your code here
if len(matrix)==0:
return False
n,m=len(matrix),len(matrix[0])
start,end = 0,n*m-1
while start+1< end:
mid = (start + end)/2
x,y = mid/m,mid%m
if matrix[x][y]<target:
start = mid
else:
end = mid
x,y = start/m,start%m
if matrix[x][y]==target:
return True
x,y = end/m,end%m
if matrix[x][y] == target:
return True
return False

总耗时: 261 ms

更新

可每次去除一行或者一列,这样划分的形式解题

时间复杂度O(M+N)

public class Solution {
/**
* @param matrix, a list of lists of integers
* @param target, an integer
* @return a boolean, indicate whether matrix contains target
*/
public boolean searchMatrix(int[][] matrix, int target) {
// write your code here
if(matrix == null || matrix.length == 0 || matrix[0].length ==0)
return false;
int row = 0;
int col = matrix[0].length-1;
return searchMatrix(matrix,row,col,target);
}
// 右上角开始是找
public boolean searchMatrix(int[][] mat,int row,int col,int target){
if(row<0 || row>= mat.length || col<0 || col>mat[0].length)
return false;
if(mat[row][col] == target)
return true;
else if(mat[row][col] < target)
return searchMatrix(mat,row+1,col,target);
else
return searchMatrix(mat,row,col-1,target);
}
}

该成递归形式

注意下面的两个while循环

public class Solution {
/**
* @param matrix, a list of lists of integers
* @param target, an integer
* @return a boolean, indicate whether matrix contains target
*/
public boolean searchMatrix(int[][] matrix, int target) {
// write your code here
if(matrix == null || matrix.length == 0 || matrix[0].length ==0)
return false;
int row = 0;
int col = matrix[0].length-1;
// 注意下面两个while 循环 row col 都要判断的
while(row< matrix.length&& col>=0){
while(row< matrix.length&& col>=0){
if (matrix[row][col] == target){
return true;
}else if(matrix[row][col] > target){
col--;
}else{
row++;
}
}
}
return false;
} }

lintcode :搜索二维矩阵的更多相关文章

  1. lintcode:搜索二维矩阵II

    题目 搜索二维矩阵 II 写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数. 这个矩阵具有以下特性: 每行中的整数从左到右是排序的. 每一列的整数从上到下是排序的. 在每一行或每一列中没 ...

  2. LintCode-38.搜索二维矩阵 II

    搜索二维矩阵 II 写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数. 这个矩阵具有以下特性: 每行中的整数从左到右是排序的. 每一列的整数从上到下是排序的. 在每一行或每一列中没有重复 ...

  3. LeetCode74.搜索二维矩阵

    74.搜索二维矩阵 描述 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值.该矩阵具有如下特性: 每行中的整数从左到右按升序排列. 每行的第一个整数大于前一行的最后一个整数. 示例 示 ...

  4. LeetCode:搜索二维矩阵【74】

    LeetCode:搜索二维矩阵[74] 题目描述 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值.该矩阵具有如下特性: 每行中的整数从左到右按升序排列. 每行的第一个整数大于前一行的 ...

  5. Leetcode 240.搜索二维矩阵II

    搜索二维矩阵II 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target.该矩阵具有以下特性: 每行的元素从左到右升序排列. 每列的元素从上到下升序排列. 示例: 现有 ...

  6. leetcode-240搜索二维矩阵II

    搜索二维矩阵II class Solution: def searchMatrix(self, matrix, target): """ :type matrix: Li ...

  7. Leetcode之二分法专题-240. 搜索二维矩阵 II(Search a 2D Matrix II)

    Leetcode之二分法专题-240. 搜索二维矩阵 II(Search a 2D Matrix II) 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target.该矩阵 ...

  8. LeetCode 74. 搜索二维矩阵(Search a 2D Matrix)

    74. 搜索二维矩阵 74. Search a 2D Matrix 题目描述 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值.该矩阵具有如下特性: 每行中的整数从左到右按升序排列. ...

  9. LeetCode 240. 搜索二维矩阵 II(Search a 2D Matrix II) 37

    240. 搜索二维矩阵 II 240. Search a 2D Matrix II 题目描述 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target.该矩阵具有以下特性 ...

随机推荐

  1. NSS_11 Server Error in '/' Application

    昨天手贱在Home/Index下点了下鼠标,set as start page,然后程序一直运行不起来, 一度以为mvc的route失效了, 一直报一个错误如下:

  2. Nginx 之并发优化

    客户端/服务端 连接数 ulimit -n 100000 nginx 链接数 10240 个 worker_connections 10240;允许打开文件数worker_processes 1;wo ...

  3. python 内置模块之hashlib、hmac、uuid

    一.hashlib md5和sha算法通过消息摘要算法生成定长的消息摘要,消息摘要算法是不可逆的.但同一段消息通过摘要算法后得到的值是一样的,可一通过比对消息摘要验证数据的完整性. sha算法比MD5 ...

  4. 从new Function创建函数联想到MVC模式

    我们知道任何一个自定义函数都是Function构造器的实例,所以我们可以通过new Function的方式来创建函数,使用语法很简单, new Function(形参1, 形参2, ..., 形参N, ...

  5. XAML 概述四

    这一节我们来简单介绍一下XAML的加载和编译,它包括如下三种方式:  · 只使用代码  · 使用代码和未编译的XAML  · 使用代码和编译过的BAML 一. 只使用代码 我们首先创建一个简单的控制台 ...

  6. 管理口令(P):[INS-30001] ADMIN口令为空之Oracle安装

    在安装oracle database11g 发行版的时候出现下面这个问题. 无论怎么输入密码都提示有问题,都输入得鬼火了!去百度了一下,果然有命名规则的 规则如下:小写字母+数字+大写字母

  7. VirtualBox中虚拟Ubuntu添加新的虚拟硬盘

    VirtualBox中装好Ubuntu后,发现硬盘空间不够使用 了.以下是搜集整理的解决办法: 1. 添加新硬盘 设置 -> Storage -> SATA控制器->右击,选择&qu ...

  8. Enum(枚举)示例

    package main; public class EnumTest { /**     * 普通枚举     */    public enum ColorEnum {        red, g ...

  9. 初解DLL基本知识

    1.DLL基本理论 在Windows操作系统中,几乎所有的内容都是以DLL的形式存在的. 1.DLL基本概念 语言程序要从目标代码(.obj)外部引用函数,可以通过俩种途径实现——静态链接和动态链接. ...

  10. VBS基础篇 - 条件语句

    经常地,当我们编写代码时,我们需要根据不同的判断执行不同操作,我们可以使用条件语句完成这个工作. If...Then...Else 在下面的情况中,您可以使用 If...Then...Else 语句: ...