74. Search a 2D Matrix
来源:互联网 发布:java与模式 云盘 编辑:程序博客网 时间:2024/06/05 00:53
问题描述
- 给定一个矩阵和目标值,其中矩阵满足:矩阵每行的元素都保持从小到大的顺序;矩阵每行第一个元素比上一行最后一个元素要大。寻找该目标值是否村在矩阵中。
解题思路
由题意可以得知,矩阵中的每行元素和每列元素都保持递增,因此可以利用两次二分查找来求解。现在第一列中寻找处目标值所在的行,然后在该行中寻找目标值。
代码
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix==null || matrix.length==0 || matrix[0].length==0) return false; int row=matrix.length; int col=matrix[0].length; int top=0; int bottom=row-1; while(top<bottom){ int middle=top+(bottom-top)/2; if(matrix[middle][0]>target){ bottom=middle; }else if(matrix[middle][0]==target) return true; else top=middle+1; } //该处是判断top是否恰好位于目标行的下一行;是否恰好位于目标行,是否恰好等于目标值 if(matrix[top][0]>target){ if(top==0) return false; row=top-1; } else if(matrix[top][0]==target) return true; else row=top; int left=0; int right=col-1; while(left<right){ int middle=left+(right-left)/2; if(matrix[row][middle]>target){ right=middle; }else if(matrix[row][middle]==target) return true; else left=middle+1; } if(matrix[row][left]==target) return true; return false; }}
阅读全文
0 0
- LeetCode 74. Search a 2D Matrix
- [LeetCode]74.Search a 2D Matrix
- LeetCode --- 74. Search a 2D Matrix
- [Leetcode] 74. Search a 2D Matrix
- [leetcode] 74.Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- Leetcode 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix LeetCode
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- leetcode 74. Search a 2D Matrix
- android瀑布流
- Oracle第五章多表链接习题答案
- Visual Studio 2015常用快捷键
- freemarker与spring整合中.<bean>的配置.主要看相对路径
- linux下的so、o、lo、a、la文件的区别
- 74. Search a 2D Matrix
- Java操作符----学习笔记
- Git常用命令速查表
- Java篇--集合
- Java基础6-this和super的区别
- Oracle第六章 分组函数习题答案
- 使用Virtualenv搭建python虚拟开发环境介绍
- PAT 乙等 1034 有理数四则运算
- 使用python模拟登登录网站