[LintCode] Search a 2D Matrix
2015-10-30 07:07
411 查看
Search a 2D Matrix
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.
Example
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given
target = 3, return
true.
Challenge
O(log(n) + log(m)) time
SOLUTION:
这题看到排序数组,就有可能用二分法,然后看到challenge是logn + logm的,就肯定是二分了,第一眼看上去是应该两个二分,找到在哪一行,再在这一行里找,但是,仔细看题目,这个matrix是绝对递增的,就是第二行第一个数绝对大于迪一行最后一个数,也就是说,把每一行都摆在一起,就是一个连续的排列的递增的数组。。。这就好办了,一个binary search就解决了。
然后就是怎么把matrix表示成一行,怎么表示end。
end 可以等于 (行数*列数 -1),然后对应的A[mid] = matrix[mid/行数] [mid%行数] : 第一个行数,就是直接用除法,看有几个行就是在第几行;然后mid去%一下,就是看它在这一行的什么位置。
最后看代码:
public class Solution { /** * @param matrix, a list of lists of integers * @param target, an integer * @return a boolean, indicate whether matrix contains target */ public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0){ return false; } if (matrix[0] == null || matrix[0].length == 0){ return false; } int row = matrix.length; int column = matrix[0].length; int start = 0; int end = matrix.length * matrix[0].length - 1; while (start + 1 < end){ int mid = start + (end - start) / 2; if (matrix[mid / column][mid % column] == target){ return true; } if (matrix[mid / column][mid % column] > target){ end = mid; } if (matrix[mid / column][mid % column] < target){ start = mid; } } if (matrix[start / column][start % column] == target){ return true; } if (matrix[end / column][end % column] == target){ return true; } return false; } }
View Code
相关文章推荐
- [CareerCup] 13.3 Virtual Functions 虚函数
- Do You Have Any Question for me
- 8.1 Triple Stair
- 使用androidstudio自带的git插件进行版本控制图文详解
- Generate Parentheses - LeetCode
- 115. Distinct Subsequences (String; DP)
- 国企离职!到了放手的时候!——北漂18年(30)
- 夺命雷公狗jquery---53--jQuery里的ajax的底层实现POST请求
- 夺命雷公狗jquery---52--jQuery里的ajax的底层实现GET请求
- Swift网络开发之NSURLSession学习笔记
- 夺命雷公狗jquery---51-each遍历图片
- [CareerCup] 13.2 Compare Hash Table and STL Map 比较哈希表和Map
- 范例解析:学习Android的IPC主板模式
- 范例解析:学习Android的IPC主板模式
- 夺命雷公狗jquery---50获取div元素并且通过each方法遍历
- [C++] Abstract Factory Pattern 实作
- 21款酷炫的数据可视化工具
- 33款可用来抓数据的开源爬虫软件工具
- Snap.svg – 现代 Web 开发必备的 JavaScript SVG 库
- Mybatis 逆向工程