博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode------Search a 2D Matrix
阅读量:7069 次
发布时间:2019-06-28

本文共 1940 字,大约阅读时间需要 6 分钟。

标题: Search a 2D Matrix
通过率 31.3%
难度 中等

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.

 

For example,

Consider the following matrix:

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

Given target = 3, return true.

本题思路清晰,就是再一个二维数组中找某个元素,那么立即想到了二分法,关键点,按行算,第k个元素的行数等于k/列数,列数等于k%列数。

还有一种思路就是,每一行的开头一定比上一行全部元素都大,那么从最后一行的第一个开始,每次比较每行的第一个,找到第一个比target小的元素,也就说明了target若存在一定在那一行,

1、二分法查找代码如下:

1 public class Solution { 2     public boolean searchMatrix(int[][] matrix, int target) { 3         if(matrix==null || matrix.length==0 || matrix[0].length==0)  4             return false; 5   6         int m = matrix.length; 7         int n = matrix[0].length; 8   9         int start = 0;10         int end = m*n-1;11  12         while(start<=end){13             int mid=(start+end)/2;14             int midX=mid/n;15             int midY=mid%n;16  17             if(matrix[midX][midY]==target) 18                 return true;19  20             if(matrix[midX][midY]

2、查找第一个小的数:

1 public class Solution { 2     public boolean searchMatrix(int[][] matrix, int target) { 3         int m=matrix.length; 4         int n=matrix[0].length; 5         int i=m-1; 6         int j=0; 7         while(i>=0){ 8             if(matrix[i][0]>target)i--; 9             else break;10         }11         if(i<0)return false;12         while(j

3、python代码:

1 class Solution: 2     def searchMatrix(self, matrix, target): 3         i, j = 0, len(matrix[0]) - 1 4         while i < len(matrix) and j >= 0: 5             if target < matrix[i][j]: 6                 j -= 1 7             elif target > matrix[i][j]: 8                 i += 1 9             else:10                 return True11         return False

 

转载于:https://www.cnblogs.com/pkuYang/p/4283345.html

你可能感兴趣的文章
图解HTTP
查看>>
python基础篇之Numpy
查看>>
null和undefined小记
查看>>
那些年 Qzone
查看>>
设计模式系列 1——StaticFactory(静态工厂),AbstractFactory(抽象工厂)
查看>>
【js基础】创建对象的几种常见模式(工厂模式,构造函数模式,原型模式,构造原型组合模式)...
查看>>
Spotlight on unix 安装
查看>>
用iTerm快速链接远程服务器
查看>>
DNS服务器:主要介绍DNS的服务原理以及安装及其主从配置
查看>>
一.Nginx的特性和一些知识点
查看>>
完整的 AJAX 写法(支持多浏览器)
查看>>
MongoDB基本操作
查看>>
sqlite基础API
查看>>
找出一个字符串中最长连续相同子串
查看>>
单链表的建立/测长/打印/删除/排序/逆序/寻找中间值
查看>>
针对上次表格编辑的打印问题及解决方案
查看>>
gradle-TestNG配置
查看>>
离线 + 位优化 - SGU 108 Self-numbers 2
查看>>
Flask 视图,中间件
查看>>
DevExpress TreeList 禁止节点拖动到其他节点上
查看>>