[算法][LeetCode]Search a 2D Matrix——二维数组的二分查找
来源:互联网 发布:淘宝开店认证怎 编辑:程序博客网 时间:2024/05/17 02:49
题目要求
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
.
分析
一开始写的时候把他拆分成了两个二分查找,先纵向找,再横向找。纵向的二分查找比较复杂,要确定是在某个坐标上,或者在两个坐标之间。
后来找到一个更好的方法,就是把二维数组的坐标转化成一位数组,整体进行二分查找,程序更简单,复杂度也更低了。
Java代码
public boolean searchMatrix(int[][] matrix, int target) {if (matrix.length == 0 || matrix[0].length == 0) {return false;}int xLength = matrix[0].length;int min = 0;int max = matrix[0].length * matrix.length - 1;int x, y, current;while (min <= max) {current = (min + max) / 2;y = current / xLength;x = current % xLength;if (matrix[y][x] == target) {return true;} else if (target < matrix[y][x]) {max = current - 1;} else {min = current + 1;}}return false;}
- [算法][LeetCode]Search a 2D Matrix——二维数组的二分查找
- leetcode——Search a 2D Matrix 二维有序数组查找(AC)
- Leetcode刷题记—— Search a 2D Matrix(在二维数组里查找)
- 字符串算法——二维有序数组中查找目标值(Search a 2D Matrix)
- 字符串算法——查找二维数组中元素(Search a 2D Matrix II)
- (二维数组中查找target)LeetCode#74. Search a 2D Matrix #240. Search a 2D Matrix II
- LeetCode-74-Search a 2D Matrix 二维二分
- [LeetCode]—Search a 2D Matrix 有序二维矩阵中查找目标值
- Search a 2D Matrix(在二维数组中查找)
- 二分查找——Search a 2D Matrix
- 【LeetCode】Search a 2D Matrix && 【九度】题目1384:二维数组中的查找
- Leetcode 74 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(二分查找)-Medium
- 第一个 Swing 程序
- listener.ora/sqlnet.ora/tnsnames.ora配置文件详解
- 选择排序
- 百度地图:根据范围和检索词发起范围搜索
- hdu-1200-To and Fro
- [算法][LeetCode]Search a 2D Matrix——二维数组的二分查找
- 存储快照
- hdu1181(变形课)
- 常见的数据结构java实现
- windbg+winXP 双机调试配置
- HashMap的使用
- CV牛人牛事简介
- 杭电OJ_A+B
- preloader打印调试语句