您的位置:首页 > 其它

LeetCode - 240. Search a 2D Matrix II

2016-06-30 11:09 375 查看
矩阵中两行或者两列之间的元素的大小并没有一定的规律,所以二分法不太好用,直接用74. Search a 2D Matrix的解法二即可,时间复杂度为O(n + m),代码如下:

public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return false;
}

int rows = matrix.length;
int cols = matrix[0].length;
int i = 0;
int j = cols - 1;

while(i < rows && j >= 0){
if(matrix[i][j] == target){
return true;
}else if(matrix[i][j] < target){
i++;
}else{
j--;
}
}

return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息