Search a 2D matrix
来源:互联网 发布:换手率软件 编辑:程序博客网 时间:2024/04/19 09:24
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
.
思路:利用matrix结构,倒着搜索,O(m+n);
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null || matrix[0].length == 0) return false; int m = matrix.length; int n = matrix[0].length; int x = 0; int y = matrix[0].length-1; while(y>=0 && x<m){ if(matrix[x][y]<target){ x++; } else if(matrix[x][y] > target){ y--; } else { return true; } } return false; } }
但是这题最优解法是binary search:
思路: 用binary search,将二维拉伸成一维,然后动态算坐标。
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if(matrix == null || matrix.length == 0) return false; int m = matrix.length; int n = matrix[0].length; int start = 0; int end = m*n-1; while(start<=end){ int mid = start +(end-start)/2; int x = mid/n; int y = mid%n; if(matrix[x][y] > target){ end = mid-1; } else if(matrix[x][y] < target){ start = mid+1; } else { return true; } } return false; } }
0 0
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D matrix
- Search a 2D matrix
- DLL编写教程
- Delphi 调用 c编写的动态链接库,结构体指针作为参数
- POJ 1860 Currency Exchange(最短路 Bellman-Ford)
- 感冒了
- java基础
- Search a 2D matrix
- 多线程中的信号机制--sigwait()函数
- CRM上线之路 走上了CRM实施顾问-第117天上班 -第24周
- (二) 算法分析基础
- 人之初,性本善
- 包含.cpp而不是.h
- 再不学习就跟人聊不上了。。。
- 异步串行通讯和同步串行通讯区别
- 我那忧伤而又文艺的高中时代