LeetCode|Search a 2D Matrix
来源:互联网 发布:php框架怎么用 编辑:程序博客网 时间:2024/05/01 18:37
题目
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]]
思路
我这里提供了3个解法
1.解法一就是一个一个搞,大家都会的
2.解法二就是先找每一行的最后一个数字,因为这个2维数组是一个有序的,所以通过判断每一行的最后一个数字可以知道我们要比较的数字在不在当前行
步骤: 一。如果在这一行,那么从这一行的最后一列往前面移动,如果遍历过了该行的所有列,而且没有找到,那么最后的结果就是没有找到
二。如果不在这一行,那么移动到下一行,然后在比较。
3.解法三就是用二分法来做。把2维数组看成是一维数组。
代码
解法一就不弄了,直接从解法二开始
解法二:
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { int row = 0; int col = matrix[0].length-1; for(;row< matrix.length&&col>=0;) { if(matrix[row][col] == target) return true; else if ( matrix[row][col] < target) { row++; } else { col--; } } return false; } }
解法三:
public class Solution { public boolean searchMatrix(int[][] matrix, int target) {int row = matrix.length;int col = matrix[0].length;int end = row * col -1;int begin = 0;while( begin <= end ){int middle = ( end +begin )/2;if( matrix[middle/col][middle%col] == target){return true;}else if (matrix[middle/col][middle%col] < target){begin = (middle/col)*col+middle%col+1;}else{end = (middle/col)*col+middle%col-1;}}return false; }}
0 0
- [leetcode][Search] Search a 2D Matrix
- LeetCode: Search a 2D Matrix
- LeetCode Search a 2D Matrix
- [Leetcode] Search a 2D Matrix
- LeetCode : Search a 2D Matrix
- [LeetCode] Search a 2D Matrix
- Leetcode 74 Search a 2D Matrix
- leetcode 90: Search a 2D Matrix
- [LeetCode]Search a 2D Matrix
- [Leetcode] Search a 2-D matrix
- [Leetcode]Search a 2D Matrix
- [leetcode]Search a 2D Matrix
- LeetCode-Search a 2D Matrix
- [leetcode] Search a 2D Matrix
- LeetCode - Search a 2D Matrix
- LeetCode:Search a 2D Matrix
- LeetCode 74: Search A 2D Matrix
- leetcode之Search a 2D Matrix
- 复制的深意
- 下载谷歌浏览器(Chrome)扩展crx文件最简单的方法~
- EasyUI网上资源(WebUI)
- 二维码、条形码扫描—ZXing
- Mysql中文乱码问题完美解决方案
- LeetCode|Search a 2D Matrix
- 【走进Lua的世界之六】Lua调用C++函数
- 嵌入式的一些学习建议
- Socket深入剖析
- 在我的Ubuntu上移植SQLite3.3.6,编译成静态库
- 深入浅出之正则表达式(一)
- 模拟Delta-Sigma的差分原理做的PWM C51程序
- 如何安装 Tomcat 于 Windows、Mac、Ubuntu 三大系统中
- 线性结构的顺序存储的实现