【LeetCode题目记录-13】二分搜索排序后的二维数组
2014-09-24 12:12
591 查看
Search a 2D Matrix
Writean 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.
【分析-原创】
/** * 创建时间:2014年9月24日 上午11:26:06 项目名称:Test * * @author Cao Yanfeng * @since JDK 1.6.0_21 类说明: 查找排序后的二维矩阵是否存在一个数 应用两层的二分查找,第一层是查找行 */ public class FindMatrixTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[][] matrix = { { 1, 3, 5, 7 }, { 10, 11, 16, 20 }, { 23, 30, 34, 50 } }; System.out.println(searchMatrix(matrix, 13)); } public static boolean searchMatrix(int[][] matrix, int target) { int m = matrix.length; int n = matrix[0].length; int i = 0, j = m - 1; while (i <= j) { int middleRow = i + ((j - i) >> 1); if (target < matrix[middleRow][0]) { j = middleRow - 1; continue; } else if (target > matrix[middleRow][n - 1]) { i = middleRow + 1; continue; } else if (target >= matrix[middleRow][0] && target <= matrix[middleRow][n - 1]) { return find(matrix[middleRow], 0, n - 1, target); } } return false; } public static boolean find(int[] matrixRow, int start, int end, int target) { while (start <= end) { int middle = start + ((end - start) >> 1); if (matrixRow[middle] == target) { return true; } else if (matrixRow[middle] > target) { end = middle - 1; } else if (matrixRow[middle] < target) { start = middle + 1; } } return false; } }
相关文章推荐
- 【LeetCode题目记录-9】排序后的数组生成平衡的二叉搜索树
- leetcode 刷题目,总结,记录,备忘 13
- 【LeetCode题目记录-8】从排序后的单链表中去除重复元素
- 【LeetCode题目记录-10】已排序的数组去除重复元素
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目4
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目5
- 九度OJ月赛---题目1534:数组中第K小的数字 (二分搜索)
- Fence Rails USACO 4.1(继续阵亡,DFSID+二分搜索+剩余记录)
- [LeetCode] 从排序的单链表到平衡搜索二叉树
- 【LeetCode题目记录-3】字符串中最长的没有重复字符的子串
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目3
- 在二分搜索应用于未排序的数组时加入部分检测程序—编程珠玑第五章习题5
- 【LeetCode题目记录-5】二叉树是否相同
- uva 10474 - Where is the Marble?(排序,二分搜索)
- HDOJ 题目2199Can you solve this equation?(二分搜索)
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目6
- 二分搜索树排序binary search sorting的c++实现
- [算法][LeetCode]Search a 2D Matrix——二维数组的二分查找
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目8