【leetcode】Array——Search a 2D Matrix(74)

来源:互联网 发布:ps -ef|grep java 编辑:程序博客网 时间:2024/05/22 05:34

题目:

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.


思路:两次binary search,第一次查询第一列,判断target可能出现在哪一行,然后再binary search该行。

第一次提交没过,因为没有考虑到如果target<matrix[0][0],第一次binary search后确定的行会是-1,导致后面ArrayIndexOutOfBoundsException: -1

代码:

    public boolean searchMatrix(int[][] matrix, int target) {        int rows=matrix.length;        if(rows==0)        return false;        int lines=matrix[0].length;                //search first element of each row        int up=0,down=rows-1;        while(up<=down){        int mid = up + ((down-up)>>1);        if(matrix[mid][0]==target)        return true;        if(target<matrix[mid][0])        down=mid-1;        else        up=mid+1;        }        if(down==-1)        return false;        //search the row        int left=0,right=lines-1;        while(left<=right){        int mid = left+((right-left)>>1);        if(matrix[down][mid]==target)        return true;        if(target<matrix[down][mid])        right=mid-1;        else        left=mid+1;        }        return false;    }
改进:不要把matrix看成是二维数组

public class Solution {        public boolean searchMatrix(int[][] matrix, int target) {            if (matrix == null || matrix.length == 0) {                return false;            }            int start = 0, rows = matrix.length, cols = matrix[0].length;            int end = rows * cols - 1;            while (start <= end) {                int mid = (start + end) / 2;                if (matrix[mid / cols][mid % cols] == target) {                    return true;                }                 if (matrix[mid / cols][mid % cols] < target) {                    start = mid + 1;                } else {                    end = mid - 1;                }            }            return false;        }    }
leetcode链接:https://leetcode.com/discuss/10735/dont-treat-it-as-a-2d-matrix-just-treat-it-as-a-sorted-list

0 0
原创粉丝点击