[leetcode] Search a 2D matrix

来源:互联网 发布:时间同步软件apk 编辑:程序博客网 时间:2024/06/16 11:57

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.

思路:很容易发现所有数已经排过序,则可以用二分查找,注意将index转化成二维坐标。

public class Solution {    public int[] findpos(int num, int row, int col){        int[] pos = new int[2];        pos[0] = num / col;        pos[1] = num % col;        return pos;    }    public boolean searchMatrix(int[][] matrix, int target) {        int row = matrix.length;        int col = matrix[0].length;        int total = row*col;        int hi = total - 1;        int low = 0;        while(low <= hi){            int mid = (low + hi)/2;            int[] pos = findpos(mid, row, col);            int number = matrix[pos[0]][pos[1]];            if(number == target)                return true;            else if(number < target)                low = mid + 1;            else                hi = mid - 1;        }        return false;    }}


0 0
原创粉丝点击