leetcode_74_搜索二维矩阵@@二分

leetcode_74_搜索二维矩阵@@二分_第1张图片

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

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

		while (i < matrix.length && j >= 0) {
			if (matrix[i][j] == target) {
				return true;
			} else if (matrix[i][j] > target) {
				j--;
			} else {
				i++;
			}
		}
		return false;
	}
}
class Solution {
   	public boolean searchMatrix(int[][] matrix, int target) {

		int m = matrix.length;
		if (m == 0)
			return false;
		int n = matrix[0].length;
		if (n == 0)
			return false;

		int l = 0;
		int r = m * n - 1;
		while (l < r) {
			int mid = (l + r + 1) >> 1;
			if (matrix[mid / n][mid % n] > target) {
				r = mid - 1;
			} else {
				l = mid;
			}
		}
		return matrix[l / n][l % n] == target;

	}
}

你可能感兴趣的:(数据结构与算法,二分法)