您的位置:首页 > 其它

LeetCode Search a 2D Matrix I,II,III (74,240)

2016-10-15 00:00 369 查看
今天面了百度,我确实目前没有这个实力,但是被拒了人总是很难受的

看以后吧

这是今天百度面的两道算法题,一搜,LeetCode上果然有原题

说实话我对自己的算法能力还是比较有自信的(虽然结果不是很理想)

先看第一道题吧

74. 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.

For example,

Consider the following matrix:

[
[1,   3,  5,  7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]

Given target =
3
, return
true
.

每一行的数字都一定比前面那行所有数字要大

直接的思路就是用二分查找,在列上找一次,然后在行上找一次,就是O(logm+logn)

public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix==null) return false;
int m = matrix.length;
int n = matrix[0].length;
if(target<matrix[0][0] || target>matrix[m-1][n-1]) return false;
int low = 0;
int high = m-1;
while(low<=high){
int mid = (low+high)/2;
if(matrix[mid][0]==target){
return true;
}else if(matrix[mid][0]<target){
low = mid+1;
}else{
high = mid-1;
}
}
int row = low-1;
low = 1;
high = n-1;
while(low<=high){
int mid = (low+high)/2;
if(matrix[row][mid]==target){
return true;
}else if(matrix[row][mid]<target){
low = mid+1;
}else{
high = mid-1;
}
}
return false;
}
}

在面试时我确实第一时间就想的这个,但是面试官不是很满意,一直催我优化

能够很快想到的优化可能是,将二维数组拉直成一维数组,以一维数组的方式去做二分查找

乍一想,这不仍然是O(logmn),我就没回答这个,不知道是不是因为没能答这个做法而悲剧的呢

再看第二道吧

240. Search a 2D Matrix II

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 in ascending from left to right.

Integers in each column are sorted in ascending from top to bottom.

For example,

Consider the following matrix:

[
[1,   4,  7, 11, 15],
[2,   5,  8, 12, 19],
[3,   6,  9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]

Given target =
5
, return
true
.

方法1:右上角或左下角搜索

以右上角为例,如果target大于他,则必定往下搜索;如果target小于它,则必定往左搜索

到矩阵的边上搜索结束,所以是O(m+n)

非常简单明了的方法

方法2:分治法

这道题也算分治法的典型了,对于最中间的元素来说,如果target大于它,则左上角一块矩阵可以去除;如果target小于它,则右下角一块矩阵可以去除

每次将问题分成3份的1/4大小,T(n) = 3T(n/4) ,具有O(n^log3)的复杂度

代码就不给了吧
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: