您的位置:首页 > 其它

(二维数组中查找target)LeetCode#74. Search a 2D Matrix #240. Search a 2D Matrix II

2017-06-09 08:01 330 查看
题目:给定一个二维数组matrix和一个target,二维数组的每行的元素都是从左到右递增,每一行的第一个元素都大于上一行的最后一个元素。如下所示

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


难度:Medium

思路:根据数组元素的大小规律,可以从第0行第n列(n=matrix[0].lenght-1)开始搜索,然后不断更新i和j

代码:

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){
j--;
}else{
i++;
}
}
return false;
}
}


Search a 2D Matrix II

数组的特点:每行从左到右递增,每列从上到下递增
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: