[Leetcode] Search a 2D Matrix (Java)

来源:互联网 发布:淘宝做一张海报多少钱 编辑:程序博客网 时间:2024/06/09 18:36

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.

在矩阵中找元素,矩阵满足条件:

1)每行都是有序的(递增);

2)下一行的首元素的值>上一行尾元素的值。

二分查找

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



0 0